changeset 17:4d8d124528f2

fix ppb_cond_counter
author Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp>
date Mon, 06 Jan 2014 16:15:05 +0900
parents 57650a6829a1
children 7efe4455deaa
files parallel_processing/ppb_cond_counter/ppb_cond_counter.c
diffstat 1 files changed, 22 insertions(+), 15 deletions(-) [+]
line wrap: on
line diff
--- 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 <stdio.h>
 #include <pthread.h>
 #include <unistd.h>
-#include <semaphore.h>
 
 #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;
 }