# HG changeset patch # User Masataka Kohagura # Date 1388998256 -32400 # Node ID a9534f217a0c3219324b13ac86312d53bc738ad6 # Parent 7efe4455deaa425938e60327779b51ca690396ba add some files diff -r 7efe4455deaa -r a9534f217a0c parallel_processing/ppb_cond_queue/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parallel_processing/ppb_cond_queue/Makefile Mon Jan 06 17:50:56 2014 +0900 @@ -0,0 +1,11 @@ +TARGET = ppb_cond_queue +CC = clang +CPPFLAGS = -g -O0 + +$(TARGET): $(TARGET).o + $(CC) -g -O0 -o $@ $< +$(TARGET).o: $(TARGET).c + +clean: + rm -f $(TARGET) + rm -f *.o diff -r 7efe4455deaa -r a9534f217a0c parallel_processing/ppb_cond_queue/ppb_cond_queue.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parallel_processing/ppb_cond_queue/ppb_cond_queue.c Mon Jan 06 17:50:56 2014 +0900 @@ -0,0 +1,57 @@ +#include +#include +#include + +#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; +}