簡體   English   中英

C ++多線程數組

[英]c++ multithread array

我在做一些有趣的事情,試圖學習多線程問題。

但是Arno指出我通過process.h進行的線程不會是多線程的。

我希望做的事情是我有一個100個數組(或10,000個,我認為並不重要),並將值分配給每個線程。 例如,4個線程=每個線程分配250個值。

然后,我可以使用此填充數組進行進一步的計算。

這是我正在處理的一些代碼(不起作用)

#include <process.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <time.h>
//#include <thread>

using namespace std;

void myThread (void *dummy );

CRITICAL_SECTION cs1,cs2; // global

int main()
{

    ofstream myfile;
    myfile.open ("coinToss.csv");

    int rNum;

    long numRuns;
    long count = 0;
    int divisor = 1;
    float holder = 0;
    int counter = 0;
    float percent = 0.0;

    HANDLE hThread[1000];


    int array[10000];

    srand ( time(NULL) );

    printf ("Runs (use multiple of 10)? ");
    cin >> numRuns;

    for (int i = 0; i < numRuns; i++)
    {
        //_beginthread( myThread, 0, (void *) (array1) );
        //???
        //hThread[i * 2] = _beginthread( myThread, 0, (void *) (array1) );
        hThread[i*2] = _beginthread( myThread, 0, (void *) (array) );

    }
     //WaitForMultipleObjects(numRuns * 2, hThread, TRUE, INFINITE);
     WaitForMultipleObjects(numRuns, hThread, TRUE, INFINITE);

}

void myThread (void *param )
{
    //thanks goes to stockoverflow
    //https://stackoverflow.com/questions/12801862/problems-passing-array-by-reference-to-threads
    int *i = (int *)param;

    for (int x = 0; x < 1000000; x++)
    {
        //param[x] = rand() % 2 + 1;
        i[x] = rand() % 2 + 1;
    }

}

誰能解釋為什么它不起作用?

對於初學者,請使用_beginthreadex而不是_beginthread,后者會在正常跳動時關閉線程句柄。 如果在開始該WFMO之前關閉線程句柄,則由於一個或多個句柄將無效,因此它可能會立即中斷。

其次,您的手柄列表上的i * 2有什么用? 將句柄列表發送給WFMO且其他所有句柄為NULL可能會立即出錯。

第三,WFMO的最大等待列表長度為64個線程,因此,一旦達到65個或更多線程,您的一千個線程列表就將有保證地嘔吐。您可能只想考慮限制該上限。 實際值為MAX_WAIT_OBJECTS(或接近該數值,我無法確切地記得)。

在我們甚至保護您要共享的陣列之前,僅此而已。

您應該知道rand不是線程安全的。

關於SO甚至有一篇文章: 從多個線程使用stdlib的rand()

如果您發現自己是線程安全的隨機數生成器,那么使用OpenMP進行並行循環會更好,因為它維護的線程池比使用線程API的效率高得多。

否則,可能需要將一個結構傳遞給您的線程函數,該結構為您提供數組和所需的長度:

struct ArraySlice
{
    ArraySlice( int *arr, size_t start, size_t end)
        : pBegin( arr + start )
        , pEnd( arr + end )
    {}

    int *pBegin, *pEnd;
};

然后創建您的線程...

size_t arrayLength = 1000000;
size_t sliceLength = arrayLength / numRuns;

for (size_t i = 0; i < numRuns; i++)
{
    size_t start = i * sliceLength;
    size_t end = min( start + sliceLength, arrayLength );
    ArraySlice *slice = new ArraySlice(array, start, end);
    hThread[i] = (HANDLE)_beginthread( myThread, 0, (void*)slice );
}

並在您的線程函數中:

void myThread (void *param )
{
    ArraySlice *slice = (ArraySlice*)param;
    if( !slice ) return;

    for( int *pos = slice->pBegin, *end = slice->pEnd; pos != end; pos++ )
    {
        *pos = rand();  // Except you need a thread-safe rand() function...
    }

    delete slice;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM