Linux c Implementation of producer consumer issues

Source: Internet
Author: User
Tags define printf semaphore sleep thread linux
Semaphore---Inter-thread communication/"producer Consumer" issue #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include &               lt;semaphore.h> #include <pthread.h> #define MSLEEP (x) usleep (x*1000) #define Product_speed 3 Production speed #define CONSUM_SPEED 1//consumption speed #define INIT_NUM 3//Warehouse  
Number of original products #define TOTAL_NUM 10//Warehouse capacity sem_t P_sem, C_sem, Sh_sem;  
       
int num=init_num;  
void product (void)//production product {sleep (product_speed);  
    int add_to_lib ()//Add product to warehouse {num++;//Warehouse add a msleep (500);  
return num;  
} void Consum ()//consumption {sleep (consum_speed);  
    int sub_from_lib ()//Remove product from warehouse {num--;//The quantity of products in the warehouse is reduced by one msleep (500);  
return num;        } void *productor (void *arg)  Producer Thread {while (1) {sem_wait (&AMP;P_SEM);//production signal quantity minus one product ();//Production delay Sem_wait (&sh_sem);//This semaphore is used to mutually exclusive printf ("Push into!  
        Tatol_num=%d\n ", Add_to_lib ());    
        Sem_post (&sh_sem);  Sem_post (&c_sem);  
               
        Consumption semaphore plus One} void *consumer (void *arg)//consumer thread {while (1) { Sem_wait (&c_sem);  
        The consumer signal quantity is reduced by one sem_wait (&sh_sem); printf ("Pop out!  
        Tatol_num=%d\n ", Sub_from_lib ());        
        Sem_post (&sh_sem);  
       
Sem_post (&p_sem)/producer Semaphore plus one consum ()//Consumption delay}}  
    int main () {pthread_t tid1,tid2;  
           
    Sem_init (&p_sem,0,total_num-init_num);  
           
    Sem_init (&c_sem,0,init_num);  
           
    Sem_init (&sh_sem,0,1);  
    Pthread_create (&tid1,null,productor,null); Pthread_create(&tid2,null,consumer,null);  
    Pthread_join (Tid1,null);  
    Pthread_join (Tid2,null);  
return 0; }

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.