Linux Semaphore producer Consumer Small example (Shh, I'm a rookie ~)

Source: Internet
Author: User
Tags semaphore

The rookie encounters the signal volume, rubs the spark (only then will have the spark if not ripe). So the Internet search information and see "UNIX Environment Advanced Programming" to achieve a few small examples, master do not spray! These are very well written:

Title Source: http://www.it165.net/os/html/201312/7039.html

Signal volume and usage: http://www.cnblogs.com/hjslovewcl/archive/2011/03/03/2314341.html

The distinction between mutexes and semaphore famous toilet theory: http://koti.mbnet.fi/niclasw/MutexSemaphore.html

Oh, it's exposed! I didn't mean to peep at others ...

One: A producer, a consumer, a resource situation

This situation can only use a semaphore, to generate or to consume only to try to obtain this semaphore, here is used two: Full=1 and Empty=0, two for the same with the back, 1, 0 is the initial value. Producer and consumer situations are as follows:

// Producer: p (empty)    generate resource and put it in Resource V (full)// consumer:P (full)    consumption resource V (empty)

If the producer first starts production resources, p (empty), full and empty are all 0, at this time if the consumer wants to consume, then P (full), the full is 0 sleep wait, and so on the end of the producer of the full plus 1, see the consumer poor asleep to wake it, Then the consumer is happy to lose 1 of his own.

Consumers in the process of production to be born, will be due to empty 0 and sleep, and so the end of the consumer put empty plus 1, and then the producer began to produce.

Above the good understanding, the following code:

#include <stdio.h>#include<stdlib.h>#include<unistd.h>#include<pthread.h>#include<x86_64-linux-gnu/sys/types.h>#include<x86_64-linux-gnu/sys/ipc.h>#include<x86_64-linux-gnu/sys/sem.h>intSeminite (intSemid,intvalue);intSemdelete (intsemid);intSemp (intsemid);intSEMV (intsemid);//declare a union to be usedUnion Semun {intVal/*value for Setval*/     structSemid_ds *buf;/*buffer for Ipc_stat, Ipc_set*/unsigned Short int*array;/*array for GETALL, SETALL*/     structSeminfo *__buf;/*Buffer for Ipc_info*/ };//Semaphore declareStatic intSemfullid;Static intSememptyid;Static intSource =0;//Source Definition//new Thread as a consumervoid* Child_thread (void*Arg) {    intTTT =1;  while(1) {Sleep (rand ()% +); printf ("Child no.%d Times wants to consume...\n", TTT);    Semp (Semfullid); //printf"Child no.%d times start consuming. Source =%d\n", TTT, source); SOURCE=0; printf ("Child no.%d times end consuming. Source =%d\n\n", ttt++, source);    SEMV (Sememptyid); //    }        return(void*)0;}intMainvoid){        //Create SemaphoreSemfullid = Semget ((key_t)1235,1,0666|ipc_creat); Sememptyid= Semget ((key_t)1236,1,0666|ipc_creat); Seminite (Semfullid,0); Seminite (Sememptyid,1);    pthread_t pid; Pthread_create (&pid, NULL, child_thread, NULL); inttt =1;  while(1) {Sleep (rand ()% -); printf ("parent no.%d Times wants to produce...\n", TT);    Semp (Sememptyid); //printf"parent no.%d times start producing. Source =%d\n", TT, source); SOURCE= rand ()% -; printf ("parent no.%d times end producing. Source =%d\n", tt++, source);    SEMV (Semfullid); //} semdelete (Semfullid);    Semdelete (Sememptyid); return 0;}//set semaphore as default valueintSeminite (intSemid,intvalue)    {Union Semun semunion; Semunion.val= value;//Set default semaphore    returnSemctl (Semid,0, Setval, semunion);}//Delete SemaphoreintSemdelete (intSemid)    {Union Semun semunion; returnSemctl (Semid,0, Ipc_rmid, semunion);}//Semaphore P OperationintSemp (intSemid) {    structSembuf Sembuf; Sembuf.sem_num=0;//indicate it is not semaphore arraySembuf.sem_op =-1;//Subtract OneSEMBUF.SEM_FLG =Sem_undo; returnSemop (Semid, &sembuf,1);//return value}//Semaphore V OperationintSEMV (intSemid) {    structSembuf Sembuf; Sembuf.sem_num=0;//indicate it is not semaphore arraySembuf.sem_op =1;//Subtract OneSEMBUF.SEM_FLG =Sem_undo; returnSemop (Semid, &sembuf,1);//return value}
111

Two threads, creating a new thread as a consumer. One of Unix's several semaphore functions looked half a day, a little complicated, simple and inaccurate:

//get a semaphore, the second parameter is the number of semaphores you want to create,//because the UNIX operation is a semaphore set, set to 1 No, just a semaphore.//other parameters I don't care.intSemget (key_t Key,intNum_sems,intsem_flags);//The operation of the Semaphore set, which can be used to implement the +1-1 function of P and V .intSemopintSEM_ID,structSEMBUF *Sem_ops, size_t num_sem_ops);//control of the semaphore set, such as initialization of the deleteintSemctl (intSEM_ID,intSem_num,intcommand, ...);

Run:

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.