Skip to content

Instantly share code, notes, and snippets.

@inq
Created November 12, 2013 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inq/7425535 to your computer and use it in GitHub Desktop.
Save inq/7425535 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
const int N = 100;
static pthread_mutex_t _m = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t _c = PTHREAD_COND_INITIALIZER;
static pthread_cond_t _d = PTHREAD_COND_INITIALIZER;
static int _n = N;
void *worker(void *_i)
{
int i = (int)_i;
printf("(%d)\n", i);
pthread_mutex_lock(&_m);
_n--;
pthread_cond_signal(&_c);
pthread_cond_wait(&_d, &_m);
pthread_mutex_unlock(&_m);
printf("[%d]\n", i);
}
int main()
{
pthread_t thrs[N];
int i = 0;
for(i = 0; i < N; i++)
pthread_create(thrs + i, NULL, worker, (void *)i);
pthread_mutex_lock(&_m);
while(_n > 0)
pthread_cond_wait(&_c, &_m);
pthread_cond_broadcast(&_d);
pthread_mutex_unlock(&_m);
for(i = 0; i < N; i++)
pthread_join(thrs[i], NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment