Created
November 12, 2013 04:35
-
-
Save inq/7425535 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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