All pastes #904474 Raw Edit

Mine

public text v1 · immutable
·published 2008-02-14 23:33 UTC
rendered paste body
// Include the generic stuff to run threads under win32, along with
// iostream for input/output, cstdlib for random numbers and ctime for seeding rand()

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <cstdlib> 
#include <iostream>
#include <ctime>

using namespace std;

int numberCarsCrossed=0; //Define this as a global so each thread can access it
int seed;  //Instantiated globally to avoid rand() stack nastiness


DWORD WINAPI JunctionThread (PVOID pParam){
        while(1){ //Infinitely loop this block until interrupted
                srand(seed);
                seed=rand();
                Sleep((seed%21)*100); //Sleep for a random interval between 0 and 5 seconds
                numberCarsCrossed+=1; //Count a car as having crossed the junction
        }
        return 1;
}



int _tmain(int argc, _TCHAR *argv[]){
        DWORD thread1,thread2,thread3,thread4;
        HANDLE handles[4];
        int i=0; //Used to accept keypresses
		seed= srand((unsigned)time(0));

        //Initialise threads
        handles[0]=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)JunctionThread, NULL, 0, &thread1);
        handles[1]=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)JunctionThread, NULL, 0, &thread2);
        handles[2]=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)JunctionThread, NULL, 0, &thread3);
        handles[3]=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)JunctionThread, NULL, 0, &thread4);

        cout <<"Threads created"<< endl << "Press a key to interrupt threads: ";
        cin >> i;
        
        //Close the threads
        for (int i=0; i<4; i+=1){
                CloseHandle(handles[i]);
                cout << endl <<"Thread "<< i<< " suspended"<<endl;
        }

        WaitForMultipleObjects(4, handles, TRUE, INFINITE); //Garbage collection
        cout <<"Threads collected with WaitForMultipleObjects." << endl << numberCarsCrossed << " cars crossed the junction." << endl;

        return 0;
}