/* * Example of threads and semaphores. * To compile: g++ -lpthread -lrt mutex.cpp */ #define _REENTRANT #include #include #include #include #include using namespace std; void *threadfunc(void *arg); int rand(void); sem_t twoex; int main(int argc, char *argv[]){ int count = atoi(argv[1]); int i; // counter pthread_t tid[10]; // creats an array of threads printf("count = %d\n", count); srand(time(NULL)); // seed the random number generator sem_init(&twoex, 0, 2); for(i = 1; i <= count; i++){ //create thread for each struct. Each thread has own threadfunc. pthread_create(&tid[count], NULL, threadfunc, NULL); } for(i = 1; i <= count; i++){ pthread_join(tid[count], NULL); } printf("Threads all done"); } void *threadfunc(void *arg) { int i, j; float c; int x; for(i = 1; i <= 3; i++){ sem_wait(&twoex); printf("Thread %d in there...\n", pthread_self()); for(c = 0; c <= 1000000 ;c += .1) x = x * 129834 / 1234 % 4314; printf("Thread %d outta there...\n", pthread_self()); sem_post(&twoex); sleep(rand()%4 + 2); } pthread_exit(0); }