Reputation: 427
I'm trying out Multi-threading in C for the first time, and I seem to be doing something wrong which I hope you could help me with. Here is my code:
#include "stdafx.h"
#define MAX_THREADS 2
int a[100000];
int b[200000];
void startThreads();
DWORD WINAPI populateArrayA(LPVOID data)
{
int i;
int* pA = (int*)data;
for(i = 0; i < sizeof(a) / sizeof(int); i++)
{
*pA = i;
pA++;
}
return 0;
}
DWORD WINAPI populateArrayB(LPVOID data)
{
int i;
int* pB = (int*)data;
for(i = 0; i < sizeof(b) / sizeof(int); i++)
{
*pB = i;
pB++;
}
return 0;
}
void startThreads()
{
HANDLE threads[MAX_THREADS];
DWORD threadIDs[MAX_THREADS];
threads[0] = CreateThread(NULL,0,populateArrayA,a,0,&threadIDs[0]);
threads[1] = CreateThread(NULL,0,populateArrayB,b,0,&threadIDs[1]);
if(threads[0] && threads[1])
{
printf("Threads Created. (IDs %d and %d)",threadIDs[0],threadIDs[1]);
}
WaitForMultipleObjects(MAX_THREADS,threads,true,0);
}
int main(int argc, char* argv[])
{
int i;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
startThreads();
return 0;
}
In this code, Array "b" seems to populate fine, however Array "a" does not. Sorry if the answer is something stupid!
EDIT: I just tried again, and both arrays are all '0's. Not quite sure what's going on. I'm using Visual Studio in case it's a debugging issue or something.
Cheers.
Upvotes: 2
Views: 152
Reputation: 7620
The last parameter of WaitForMultipleObjects
must be INFINITE
, not 0
.
With 0
, the function returns immediatly.
Upvotes: 4