Skip to content

Instantly share code, notes, and snippets.

@dasosjt
Last active November 1, 2017 23:58
Show Gist options
  • Save dasosjt/5c1b436024857dd62ec600737e7c15ce to your computer and use it in GitHub Desktop.
Save dasosjt/5c1b436024857dd62ec600737e7c15ce to your computer and use it in GitHub Desktop.
gcc lab9b.c -lpthread -o lab9b
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define NTHREADS 5
#define ITER 10
#define RSRC 100
#define COUNT_R 5
pthread_mutex_t mutex;
pthread_cond_t condition;
int available_resources;
int count_resources;
int decrease_count(int count)
{
if(available_resources < count)
{
return -1;
}
else
{
available_resources -= count;
return 0;
}
}
int increase_count(int count)
{
available_resources += count;
return 0;
}
void* thread_func(void* arg)
{
int iter = ITER;
int value;
for(int k = 0; k < iter; k++) // Thread consuming resources
{
pthread_mutex_lock(&mutex);
while(decrease_count(count_resources) == -1)
{
fprintf(stdout, "iter: %d with thread: %d couldnt take the resource\n", k, pthread_self ());
pthread_cond_wait(&condition, &mutex);
}
fprintf(stdout, "iter: %d with thread: %d has taken the resource\n", k, pthread_self ());
sleep(1);
fprintf(stdout, "iter: %d with thread: %d has returned the resource\n", k, pthread_self ());
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
increase_count(count_resources);
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(void)
{
int nthreads = NTHREADS;
pthread_t pthread_ids [nthreads];
available_resources = RSRC;
count_resources = COUNT_R;
if(pthread_mutex_init(&mutex, NULL) != 0)
{
fprintf(stderr, "%s\n", "pthread_mutex_init");
return 1;
}
if(pthread_cond_init(&condition, NULL) != 0)
{
fprintf(stderr, "%s\n", "pthread_cond_init");
return 2;
}
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