Linux ring buff simulates multi-threaded semaphore operation

Source: Internet
Author: User

The value of the mutex mutex variable is not 0, or 1, and can only be used to represent critical resources in both states. And the semaphore is similar to that used to indicate the available resources, the difference is that the semaphore can represent multiple available resources.

-The semaphore with a value of 2 is a special mutex.

Then the simple implementation of the signal volume represents the problem of producer consumers of multiple resource accesses.

#include <stdio.h>#include<stdlib.h>#include<unistd.h>#include<semaphore.h>#include<pthread.h>#define_size_ 128intbuf[_size_];sem_t blanks;sem_t datas;//producersvoid*producter (void*val) {    intBeg =0;  while(1) {sem_wait (&blanks); intdata = rand ()%1024x768; Buf[beg]=data; printf ("%s done ... data =%d\n", __func__,data); Sem_post (&datas); Beg= (beg+1)%_size_; Sleep (3); }    returnNULL;}//Consumervoid*consumer (void*val) {    intStart =0;  while(1) {sem_wait (&datas); intdata =Buf[start]; printf ("%s dene ... data =%d\n", __func__,data); Sem_post (&blanks); Start= (start+1)%_size_; Sleep (5); }    returnNULL;}intMainintargcChar Const*argv[]) {Sem_init (&blanks,0, _size_); Sem_init (&datas,0,0);    pthread_t Id1,id2; Pthread_create (&id1,null,producter,null); Pthread_create (&id2,null,consumer,null);    Pthread_join (Id1,null);    Pthread_join (Id2,null); Sem_destroy (&blanks); Sem_destroy (&datas); return 0;}

About mutex, synchronization and other issues, participate in the previous blog

Linux multithreading-Mutual exclusion & conditional variables and synchronization

Linux ring buff simulates multi-threaded semaphore operation

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.