我做得好玩,想学多线程 Problems passing array by reference to threadsC++多线程阵列
但阿诺指出,通过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;
}
}
任何人都可以解释为什么它不工作?
你已经注释掉了''标题,为什么?为什么不使用C++中的标准线程工具? –