# HG changeset patch # User Masataka Kohagura # Date 1388992505 -32400 # Node ID 4d8d124528f2b04439c93a262595769297c640c9 # Parent 57650a6829a1f2fce225ebb69176501e0d0caac3 fix ppb_cond_counter diff -r 57650a6829a1 -r 4d8d124528f2 parallel_processing/ppb_cond_counter/ppb_cond_counter.c --- a/parallel_processing/ppb_cond_counter/ppb_cond_counter.c Mon Jan 06 15:52:00 2014 +0900 +++ b/parallel_processing/ppb_cond_counter/ppb_cond_counter.c Mon Jan 06 16:15:05 2014 +0900 @@ -1,49 +1,56 @@ #include #include #include -#include #define MAX_THREAD_NUM 2 #define THREAD_NUM 5 -sem_t sem; +pthread_mutex_t mutex; +pthread_cond_t cond; +int thread_num = 0; -/** - * Mavericks では clang が default となっているが、書籍自体は gcc でコンパイルしている。 - * クラスタ環境に gcc が存在していたので、そこでコンパイルすると望ましい動作結果が得られた。 - * clang では・・・どうするんだろ - */ void * thread_func(void *arg) { long id = (long)arg; - /* starting semaphore and ending semaphore*/ - sem_wait(&sem); + pthread_mutex_lock(&mutex); + while (thread_num >= MAX_THREAD_NUM) pthread_cond_wait(&cond, &mutex); + thread_num++; + pthread_mutex_unlock(&mutex); + printf("Thread %ld started.\n", id); sleep(1); printf("Thread %ld finished.\n", id); - sem_post(&sem); + + pthread_mutex_lock(&mutex); + thread_num--; + pthread_cond_signal(&cond); + pthread_mutex_unlock(&mutex); + return 0; } int main() { + long i; pthread_t handle[THREAD_NUM]; - long i; /* initialize */ - sem_init(&sem, 0, MAX_THREAD_NUM); + pthread_mutex_init(&mutex, NULL); + pthread_cond_init(&cond, NULL); /* spawn thread a number of THREAD_NUM */ - for (i = 0; i < THREAD_NUM; ++i) pthread_create(&handle[i], NULL, &thread_func, (void*)i); + for (i = 0; i < THREAD_NUM; ++i) + pthread_create(&handle[i], NULL, &thread_func, (void*)i); /* wait for running all thread */ - for (i = 0; i < THREAD_NUM; ++i) pthread_join(handle[i], NULL); + for (i = 0; i < THREAD_NUM; ++i) + pthread_join(handle[i], NULL); /* destroy mutex*/ - sem_destroy(&sem); + pthread_cond_destroy(&cond); return 0; }