Producer consumer issues (thread-based and nameless semaphores)

Source: Internet
Author: User

//5. Producer Consumer issues#include <pthread.h>#include<semaphore.h>#include<unistd.h>#include<stdio.h>#defineMAX 50#defineBUFSIZETen  //Size of warehouseintbuf[bufsize]={0}; int inch=0; int  out=0;   Sem_t Full,empty; void* Producer (void*Arg) {     inti;  for(i =1; i<=max;++i) {/*Produce*/sem_wait (&Full ); buf[inch++]=i; inch%=BUFSIZE; printf ("production of%d products \ n", i); Sem_post (&empty); } pthread_exit ((void*)"Thread1 exit\n"); }  void* Comsumer (void*Arg) {     intI,data_c;  for(i =1; i<= MAX; ++i) {/*Comsumer*/sem_wait (&empty); Data_c=buf[ out++];  out%=BUFSIZE; printf ("%d products were consumed \ n", Data_c); Sem_post (&Full ); } pthread_exit ((void*)"thread2 exit\n"); }  intMainvoid)  {     void*Tret; Sem_init (&full,0,Ten); the initial value of the semaphore is 10 and the warehouse size remains consistent sem_init (&empty,0,0);     pthread_t Tid_producer,tid_comsumer; Pthread_create (&tid_producer,null,producer,null); Pthread_create (&tid_comsumer,null,comsumer,null); Pthread_join (Tid_producer,&Tret); printf ("%s\n",(Char*) Tret); Pthread_join (Tid_comsumer,&Tret); printf ("%s\n",(Char*) Tret); Sem_destroy (&Full ); Sem_destroy (&empty); return 0;}
This program must pay attention to the number of semaphores must be the same size as the storage space of the warehouse, the program two number is ten

Producer consumer issues (thread-based and nameless semaphores)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.