int out=0; int p=1;
sem_t sem_mutex; sem_tempty_sem_mutex; sem_tfull_sem_mutex; void *Producer() {
while(1) {
sem_wait(&empty_sem_mutex); sem_wait(&sem_mutex); if(p>10) p=1;
buffer[in]=p++;
printf(\ if(out==(in=(in+1)%BUFF_SIZE)) {
printf(\ }
sem_post(&sem_mutex); sem_post(&full_sem_mutex); } }
void *Consumer() {
while(1)
{
sem_wait(&full_sem_mutex); sem_wait(&sem_mutex);
printf(\ if((out=(out+1)%BUFF_SIZE)==in) {
printf(\ }
sem_post(&sem_mutex); sem_post(&empty_sem_mutex); } } int main() {
pthread_t ptid,ctid;
sem_init(&sem_mutex,0,1);//unlocksem_mutex=1;
sem_init(&empty_sem_mutex,0,10);//unlockempty_sem_mutex=10; sem_init(&full_sem_mutex,0,0);//lock printf(\
if(pthread_create(&ptid,NULL,Producer,NULL)) {
printf(\ exit(1); } else
{
printf(\ }
if(pthread_create(&ctid,NULL,Consumer,NULL)) {
printf(\ exit(1); } else {
printf(\ }
if(pthread_join(ptid,NULL)) {
printf(\ exit(1); }
if(pthread_join(ctid,NULL)) {
printf(\ exit(1); }
sem_destroy(&empty_sem_mutex); sem_destroy(&full_sem_mutex); sem_destroy(&sem_mutex); //exit the main thread
pthread_exit(NULL); return 1; }
总结:
(1)在每个程序中用于互斥的wait(mutex)和signal(mutex)必须成对出现,即对临界资源的使用前必须申请,使用后必须释放。
(2)对资源信号量empty_sem_mutex和full_sem_mutex的wait和signal操作也需要成对出现,但它们分别处于不同的进程中,以保证生产者线程和消费者线程的同步(若n=1,则生产者和消费者线程只能严格的交替执行,若n>1,则在消费者线程不执行的前提下,生产者线程最多可重复执行n次;反之消费者也同样)。