/producer/consumer problem
#include
#include
#include
#include
Int=0, in out=0;//in and out for producers and consumers to use in the buffer array subscript
Int buffer [10]=,0,0,0,0,0,0,0,0,0 {0};//buffer size of 10
Sem_t mutex, empty and full;//mutex mutex for buffer pool, the empty says the number of empty buffer, full said full buffer number
Int produce_an_item () {//for producers
Int I=5;
return i;
}
//producer
Void * producter (void * arg) {
While (1) {
Int I=produce_an_item ();//get data
Sem_wait (& amp; The empty);
Sem_wait (& amp; Mutex);
Printf (" producers read data % d \ n ", I);
Buffer [in]=I;//the data into the buffer
In=% (+ 1) in 10;//the subscript forward
Sem_post (& amp; Mutex);
Sem_post (& amp; Full);
}
}
//consumer
Void * consumer (void * arg) {
While (1) {
Sem_wait (& amp; Full);
Sem_wait (& amp; Mutex);
Int I=buffer [out].//I on behalf of the read data from a buffer
Printf (" consumers to take out the data for: % d \ n ", I);
Buffer [out]=0;//read after this set to 0
Out=(out + 1) % 10;
Sem_post (& amp; Mutex);
Sem_post (& amp; The empty);
}
}
Int main () {
//create the producer thread
Pthread_t p1, p2, p3;
Pthread_create (& amp; P1, NULL, producter, NULL);
Pthread_create (& amp; P2, NULL, producter, NULL);
Pthread_create (& amp; P3, NULL, producter, NULL);
//create the consumer process
Pthread_t c1, c2, c3 and c4.
Pthread_create (& amp; C1, NULL, consumer, NULL);
Pthread_create (& amp; C2, NULL, consumer, NULL);
Pthread_create (& amp; C3, NULL, consumer, NULL);
Pthread_create (& amp; C4, NULL, consumer, NULL);
//initialize the mutex
Sem_init (& amp; The mutex, 0, 1);
Sem_init (& amp; The empty, 0, 10);
Sem_init (& amp; Full, 0, 0);
//running thread
Pthread_join (p1, NULL);
Pthread_join (p2, NULL);
Pthread_join (p3, NULL);
Pthread_join (c1, NULL);
Pthread_join (c2, NULL);
Pthread_join (c3, NULL);
Pthread_join (c4, NULL);
return 0;
}
Programs often run up, don't know why, head all dizzy,, please help to see
CodePudding user response:
55555 people?CodePudding user response:
Don't run is what meaning compilation errors or run the didn't reflect or other?Under Linux can use GDB to debug
CodePudding user response: