Mercurial > hg > Members > masakoha > testcode
changeset 19:a9534f217a0c
add some files
author | Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp> |
---|---|
date | Mon, 06 Jan 2014 17:50:56 +0900 |
parents | 7efe4455deaa |
children | 28cac8b199cb |
files | parallel_processing/ppb_cond_queue/Makefile parallel_processing/ppb_cond_queue/ppb_cond_queue.c |
diffstat | 2 files changed, 68 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /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
--- /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 <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; +}