#include #include #include #include #include using namespace std; static int s2i(string const& str) { int ret = 0; stringstream s(str); s >> ret; return ret; } struct thread_data { int num; int seed; }; static int *values; int thrdCount=0; int thrdNum; bool done=false; CRITICAL_SECTION CritSection; CONDITION_VARIABLE ConditionVar; static DWORD WINAPI thread_proc(LPVOID data) { thread_data* i = (thread_data*)data; srand(i->seed); rand(); values[i->num] = (rand() % 200) - 100; EnterCriticalSection(&CritSection); cout << "values[" << i->num << "] = " << values[i->num] << endl; thrdCount++; if (thrdCount==thrdNum){ done=true; WakeAllConditionVariable(&ConditionVar); // Wait until the predicate is TRUE } else while(!done) { SleepConditionVariableCS(&ConditionVar, &CritSection, INFINITE); } /* Condition variables are subject to spurious wakeups (those not associated with an explicit wake) and stolen wakeups (another thread manages to run before the woken thread). Therefore, you should recheck a predicate (typically in a while loop) after a sleep operation returns. */ LeaveCriticalSection(&CritSection); int sum=0; for(int j=0;jnum << ": randon value = " << values[i->num]<<" , sum = "<< sum << "\n"; return 0; } int main(int argc, char *argv[]) { if(argc < 2) { cout << "You must specify the number of threads to create" << endl; return -1; } InitializeCriticalSection(&CritSection); InitializeConditionVariable (&ConditionVar); thrdNum = s2i(argv[1]); if(thrdNum <= 0) { cout << "You must specify a number that is > 0" << endl; return -1; } values = new int[thrdNum]; HANDLE *handles = new HANDLE[thrdNum]; thread_data *data = new thread_data[thrdNum]; for(int i = 0; i < thrdNum; ++i) { data[i].num = i; data[i].seed = rand();//could use rand_s handles[i] = CreateThread(NULL, 0, &thread_proc, data+i, 0, NULL); if(!handles[i]) { cerr << "Failed to create thread " << i << endl; return -1; } } WaitForMultipleObjects(thrdNum, handles, TRUE, INFINITE); int sum = 0; for(int j = 0; j < thrdNum; ++j) { CloseHandle(handles[j]); } delete [] handles; delete [] values; delete [] data; return 0; }