linux環形buff類比多線程訊號量操作,linuxbuff

來源:互聯網
上載者:User

linux環形buff類比多線程訊號量操作,linuxbuff

互斥鎖mutex變數的值非0即1,只能用來表示兩種狀態下的臨界資源。而訊號量是與之類似的,用來表示可用資源的,區別在於,訊號量可以表示多個可用資源的。

--值為2的訊號量也就是特殊的互斥鎖了。

那麼下邊就簡單實現訊號量表示多個資源訪問的生產者消費者問題了。

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <semaphore.h>#include <pthread.h>#define _SIZE_ 128int buf[_SIZE_];sem_t blanks;sem_t datas;//生產者void *producter(void *val){    int beg = 0;    while(1)    {        sem_wait(&blanks);        int data = rand()%1024;        buf[beg] = data;        printf("%s done... data = %d\n",__func__,data);        sem_post(&datas);        beg = (beg+1)%_SIZE_;        sleep(3);    }    return NULL;}//消費者void *consumer(void *val){    int start = 0;    while(1)    {        sem_wait(&datas);        int data = buf[start];        printf("%s dene... data = %d\n", __func__,data);        sem_post(&blanks);        start = (start+1)%_SIZE_;        sleep(5);    }    return NULL;}int main(int argc, char 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;}

關於互斥鎖,同步等問題,參加上篇部落格

《linux多線程-互斥&條件變數與同步》

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.