Skip to content

Instantly share code, notes, and snippets.

@dasosjt
Last active November 1, 2017 22:05
Show Gist options
  • Save dasosjt/c359f7687281084d2d26ecba0f438715 to your computer and use it in GitHub Desktop.
Save dasosjt/c359f7687281084d2d26ecba0f438715 to your computer and use it in GitHub Desktop.
gcc lab9a.c -lpthread -o lab9a
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define NTHREADS 5
#define ITER 10
sem_t semaphore;
void* thread_func(void* arg)
{
int iter = ITER;
int value;
for(int k = 0; k < iter; k++) // Thread consuming resources
{
sem_getvalue(&semaphore, &value);
if(value == 0)
{
fprintf(stdout, "iter: %d with thread: %d couldnt take the resource\n", k, pthread_self ());
}
sem_wait(&semaphore);
fprintf(stdout, "iter: %d with thread: %d has taken the resource\n", k, pthread_self ());
sleep(1);
sem_post(&semaphore);
fprintf(stdout, "iter: %d with thread: %d has returned the resource\n", k, pthread_self ());
}
return NULL;
}
int main(void)
{
int nthreads = NTHREADS;
pthread_t pthread_ids [nthreads];
sem_init(&semaphore, 0, 1);
for(int i = 0; i < nthreads; i++) // Create all threads
{
if(pthread_create(&pthread_ids[i], NULL, thread_func, NULL))
{
fprintf(stderr, "iter: %d couldnt create a thread\n", i);
}
else
{
fprintf(stdout, "created thread: %d\n", pthread_ids[i]);
}
}
for(int j = 0; j < nthreads; j++) // Wait for all treads
{
if(pthread_join(pthread_ids[j], NULL))
{
fprintf(stderr, "iter: %d couldnt join a thread\n", j);
}
else{
fprintf(stdout, "joined thread: %d\n", pthread_ids[j]);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment