Mercurial > hg > Applications > Grep
diff parallel_processing/ppb_cond_counter/ppb_cond_counter.c @ 16:57650a6829a1
add some files in ppb_cond_counter
author | Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp> |
---|---|
date | Mon, 06 Jan 2014 15:52:00 +0900 (2014-01-06) |
parents | parallel_processing/ppb_sem_counter/ppb_sem_counter.cc@08beb7bff036 |
children | 4d8d124528f2 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parallel_processing/ppb_cond_counter/ppb_cond_counter.c Mon Jan 06 15:52:00 2014 +0900 @@ -0,0 +1,49 @@ +#include <stdio.h> +#include <pthread.h> +#include <unistd.h> +#include <semaphore.h> + +#define MAX_THREAD_NUM 2 +#define THREAD_NUM 5 + +sem_t sem; + +/** + * Mavericks では clang が default となっているが、書籍自体は gcc でコンパイルしている。 + * クラスタ環境に gcc が存在していたので、そこでコンパイルすると望ましい動作結果が得られた。 + * clang では・・・どうするんだろ + */ +void * +thread_func(void *arg) +{ + long id = (long)arg; + + /* starting semaphore and ending semaphore*/ + sem_wait(&sem); + printf("Thread %ld started.\n", id); + sleep(1); + printf("Thread %ld finished.\n", id); + sem_post(&sem); + return 0; +} + +int +main() +{ + pthread_t handle[THREAD_NUM]; + long i; + + /* initialize */ + sem_init(&sem, 0, MAX_THREAD_NUM); + + /* 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*/ + sem_destroy(&sem); + + return 0; +}