Mercurial > hg > Members > masakoha > testcode
comparison parallel_processing/ppb_cond_queue/ppb_cond_queue.c @ 19:a9534f217a0c
add some files
author | Masataka Kohagura <e085726@ie.u-ryukyu.ac.jp> |
---|---|
date | Mon, 06 Jan 2014 17:50:56 +0900 |
parents | parallel_processing/ppb_cond_counter/ppb_cond_counter.c@7efe4455deaa |
children | d137f1823794 |
comparison
equal
deleted
inserted
replaced
18:7efe4455deaa | 19:a9534f217a0c |
---|---|
1 #include <stdio.h> | |
2 #include <pthread.h> | |
3 #include <unistd.h> | |
4 | |
5 #define MAX_THREAD_NUM 2 | |
6 #define THREAD_NUM 5 | |
7 | |
8 pthread_mutex_t mutex; | |
9 pthread_cond_t cond; | |
10 int thread_num = 0; | |
11 | |
12 void * | |
13 thread_func(void *arg) | |
14 { | |
15 long id = (long)arg; | |
16 | |
17 pthread_mutex_lock(&mutex); | |
18 while (thread_num >= MAX_THREAD_NUM) | |
19 pthread_cond_wait(&cond, &mutex); | |
20 thread_num++; | |
21 pthread_mutex_unlock(&mutex); | |
22 | |
23 printf("Thread %ld started.\n", id); | |
24 sleep(1); | |
25 printf("Thread %ld finished.\n", id); | |
26 | |
27 pthread_mutex_lock(&mutex); | |
28 thread_num--; | |
29 pthread_cond_signal(&cond); | |
30 pthread_mutex_unlock(&mutex); | |
31 | |
32 return 0; | |
33 } | |
34 | |
35 int | |
36 main() | |
37 { | |
38 long i; | |
39 pthread_t handle[THREAD_NUM]; | |
40 | |
41 /* initialize */ | |
42 pthread_mutex_init(&mutex, NULL); | |
43 pthread_cond_init(&cond, NULL); | |
44 | |
45 /* spawn thread a number of THREAD_NUM */ | |
46 for (i = 0; i < THREAD_NUM; ++i) | |
47 pthread_create(&handle[i], NULL, &thread_func, (void*)i); | |
48 | |
49 /* wait for running all thread */ | |
50 for (i = 0; i < THREAD_NUM; ++i) | |
51 pthread_join(handle[i], NULL); | |
52 | |
53 /* destroy mutex*/ | |
54 pthread_cond_destroy(&cond); | |
55 | |
56 return 0; | |
57 } |