Question: Create the file: counting_semaphore.c #include #include #include //compile and link with -pthread #include const int NUM_THREADS = 16; const int NUM_PRINTERS = 4; sem_t s;
Create the file: counting_semaphore.c
| #include #include #include #include const int NUM_THREADS = 16; const int NUM_PRINTERS = 4; sem_t s; void *run( void *ptr ) { int tid = (int) pthread_self(); int value; while(1){ printf("%d needs a printer now! ", tid); sem_getvalue(&s, &value); printf("\tsemaphore value = %d ", value); sem_wait(&s); printf("%d is printing now! ", tid); usleep(rand() % 1000); printf("%d is done printing! ", tid); sem_getvalue(&s, &value); printf("\tsemaphore value = %d ", value); sem_post(&s); printf("%d is doing something else... ", tid); usleep(rand() % 1000); } } int main() { pthread_t threads[NUM_THREADS]; sem_init(&s, 0, NUM_PRINTERS); srand(time(NULL)); int i; for(i = 0; i < NUM_THREADS; i++){ pthread_create( &threads[i], NULL, run, NULL); } for(i = 0; i < NUM_THREADS; i++){ pthread_join( threads[i], NULL); } exit(0); }
|
Compile the file:
student@Ubuntu:~/labs/lab3$ gcc -pthread counting_semaphore.c -o cs
Run the counting_semaphore program for a few seconds. Then press <Ctrl+ C> to stop the program:
student@Ubuntu:~ /labs/lab3 $ ./cs
Copy and paste the output below. Check the output for any inconsistency.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
