Mercurial > hg > Members > masakoha > testcode
view parallel_processing/ppb_cond_counter/ppb_cond_counter.c @ 18:7efe4455deaa
fix
author | Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp> |
---|---|
date | Mon, 06 Jan 2014 16:26:54 +0900 |
parents | 4d8d124528f2 |
children |
line wrap: on
line source
#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; }