Skip to content

Instantly share code, notes, and snippets.

@geekuillaume
Created March 12, 2014 10:09
Show Gist options
  • Save geekuillaume/9504128 to your computer and use it in GitHub Desktop.
Save geekuillaume/9504128 to your computer and use it in GitHub Desktop.
Thread sync challenge
#include <semaphore.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
sem_t sem;
pthread_mutex_t mut;
void thread_fct()
{
int towait;
while (42)
{
towait = rand();
printf("start %d\n", towait % 500);
usleep(towait % 500);
printf("end\n");
pthread_mutex_trylock(&mut);
if (!sem_trywait(&sem))
{
pthread_mutex_lock(&mut);
pthread_mutex_unlock(&mut);
sem_post(&sem);
}
else
{
pthread_mutex_unlock(&mut);
}
}
}
int main(int argc, char const *argv[])
{
int sem_nb;
pthread_t *thread;
sem_nb = atoi(argv[1]);
sem_init(&sem, 0, sem_nb - 1);
thread = malloc((sem_nb + 2) * sizeof(pthread_t));
for (int i = 0; i < sem_nb; ++i)
pthread_create(&thread[i], NULL, thread_fct, NULL);
for (int i = 0; i < sem_nb; ++i)
pthread_join(thread[i], NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment