diff parallel_processing/chapter3/ppb_cond_counter/ppb_cond_counter.c @ 22:508b47c8f4d8

package Chapter3
author Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp>
date Tue, 07 Jan 2014 14:30:28 +0900
parents parallel_processing/ppb_cond_counter/ppb_cond_counter.c@7efe4455deaa
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/parallel_processing/chapter3/ppb_cond_counter/ppb_cond_counter.c	Tue Jan 07 14:30:28 2014 +0900
@@ -0,0 +1,57 @@
+#include <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+
+#define MAX_THREAD_NUM 2
+#define THREAD_NUM 5
+
+pthread_mutex_t mutex;
+pthread_cond_t  cond;
+int thread_num = 0;
+
+void *
+thread_func(void *arg)
+{
+    long id = (long)arg;
+
+    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);
+
+    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];
+
+    /* initialize */
+    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);
+
+    /* wait for running all thread */
+    for (i = 0; i < THREAD_NUM; ++i)
+        pthread_join(handle[i], NULL);
+
+    /* destroy mutex*/
+    pthread_cond_destroy(&cond);
+
+    return 0;
+}