1. Casting:
Pay attention to the casting!
void myThread (void *param ) { int *i = (int *) param; for (int x = 0; x < 1000000; x++) { i[x] = rand() % 2 + 1; } }
2. Scope:
Both threads are started numRuns times. Launching them will take some time. Doing them too. main should not end without threads. You must keep track of threads using WaitForMultipleObjects . _beginthread () returns a waitable handle .
Implementation:
int main() { long numRuns; HANDLE hThread[MAX_WAIT_OBJECTS]; cin >> numRuns; // numRuns to be smaller than MAX_WAIT_OBJECTS/2!!!! for (int i = 0; i < numRuns; i++) { hThread[i * 2] = _beginthread( myThread, 0, (void *) (array1) ); hThread[i * 2 + 1] = _beginthread( myThread2, 0, (void *) (array2) ); // or better use _beginthreadex(...) } WaitForMultipleObjects(numRuns * 2, hThread, TRUE, INFINITE); // bWaitAll flag set TRUE causes this statement to wait until all threads have finished. // dwMilliseconds set to INFINITE will force the wait to not timeout. }
Thus, main will end only when all threads have completed their work.
3. Access:
Both arrays are declared in the main section, so the threads divide them. To protect access, you must introduce some kind of exclusivity. The simplest is the Critical Partition Object . When all threads2 gain access only to array2, and all flows1 gain access only to array1, I would suggest using 2 objects of the critical section. A critical section can be accessed only one thread at a time.
Implementation:
CRITICAL_SECTION cs1,cs2; // global int main() { long numRuns; HANDLE hThread[1000]; // critical section object need to be initialized before aquired InitializeCriticalSection(&cs1); InitializeCriticalSection(&cs2); cin >> numRuns; for (int i = 0; i < numRuns; i++) { hThread[i * 2] = _beginthread( myThread, 0, (void *) (array1) ); hThread[i * 2 + 1] = _beginthread( myThread2, 0, (void *) (array2) ); } WaitForMultipleObjects(numRuns * 2, hThread, TRUE, INFINITE); }
And the threads (only one shown here):
void myThread1 (void *param ) { EnterCriticalSection(&cs1);
However: The whole story is still a bit obscure. You want multiple threads to fill the same array from start to finish at the same time. It sounds strange. When using the critical section objects described here, the threads will execute one after the other anyway. What exactly are you aiming for?