این چیزی که شما نوشته اید شبه کد هست پیشنهاد می کنم از آنجایی که این برنامه بزرگ نیست مستقیما کد برای آن بنویسید و البته آن را کامپایل کنید واین که اصرار دارم که کامپایلرتون را قرار دهید به این خاطر است که احتمالا کامپایلر سمافور داره و نیاز نیست اون را پیاده کنید( البته ممکن هم هست که نداشته باشه) من کدی را که به زبان C++ نوشته شده قرار می دم تا از اون ایده بگیرید ولی باز هم تاکید می کنم که حتما کامپایلرتون را قرار دهید تا بقیه اون را استفاده کنند.
این کد در لینوکس نوشته شده و کامپایل هم شده و مشکلی نداشته است.
5) #ifdef HAVE_CONFIG_H
6) #include <config.h>
7) #endif
8)
9) #include <iostream>
10) #include <cstdlib>
11) #include <pthread.h>
12) #include <stdio.h>
13) #include <malloc.h>
14) #include <pthread.h>
15) #include <semaphore.h>
16)
17)
18) using namespace std;
19)
20)
21) int counter;
22) #define MaxSize 200
23) int count_thread;
24)
25) char arr[MaxSize] ;
26) sem_t empty , full;
27) pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER;
28)
29) int random_range(unsigned const low, unsigned const high)
30) {
31) unsigned const range = high - low + 1;
32) return low + (int)(((double)range)*rand() / (RAND_MAX + 1.0));
33) }
34)
35) void* produce (void* unused)
36) {
37) //srand(time(NULL));
38) pthread_mutex_lock (&l);
39)
40) int r = random_range(0, 25) + 'a';
41) cout << "I produce character: '" << (char)r << "'\n";
42) arr[counter]=(char)r;
43) counter++;
44)
45) pthread_mutex_unlock (&l);
46)
47) return NULL;
48) }
49)
50) void* consume (void* unused)
51) {
52) counter--;
53) cout << "I consume character: '" << arr[counter] << "'\n";
54)
55) return NULL;
56) }
57)
58) int main ()
59) {
60) int type[MaxSize];
61)
62) pthread_t threads[MaxSize];
63) counter =0;
64) int count;
65) cout <<" size of buffer:";
66) cin >> count;
67) sem_init (&empty, MaxSize, MaxSize);
68) sem_init (&full, MaxSize, 0);
69)
70) cout << "number of threads:";
71) cin >> count_thread;
72)
73) cout << "Give type of threads('1' for producer and '0' for consumer):\n";
74) for (int i=0; i<count_thread; i++)
75) cin >> type[i];
76) int sw;
77) for (int i =0 ; i < count_thread ; i++)
78) {
79) if(type[i] == 0)
80) {
81) // consumer
82) sem_wait (&full);
83) pthread_create (&(threads[i]), NULL, consume, NULL);
84) pthread_join(threads[i],NULL);
85) sem_post (&empty);
86) }
87) else
88) {
89) sem_wait (&empty);
90) pthread_create (&(threads[i]), NULL, produce, NULL);
91) pthread_join(threads[i],NULL);
92) sem_post (&full);
93) }
94)
95) }//end of for
96)
97)
98)
99) return 0;
100) }