生活随笔
收集整理的這篇文章主要介紹了
Linux学习之系统编程篇:使用信号量实现“生产者和消费者模型”
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模型中,最為關鍵的步驟是,在生產者回調函數中,未生產之前,消費者回調函數是阻塞的,阻塞方式是條件變量。
那么不使用條件變量,如何使用“信號量”實現阻塞呢?
答案是因為調用 sem_wait,當 sem == 0 時候,該線程就會阻塞。因此:生產者對應一個信號量 :sem_t produce;消費者對應一個信號量 :sem_t customer。
sem_init(&produce, 0, 2);
sem_init(&customer, 0, 0); 消費者 value = 0,表示被阻塞
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
sem_t produce
;
sem_t custom
;
typedef struct node
{int data
;struct node* next
;
}Node
;
Node
* phead
= NULL;
void* produce_fun()
{while(1){sem_wait(&produce
); Node
* node
= (Node
*)malloc(sizeof(Node
));node
->data
= rand() % 1000;node
->next
= phead
;phead
= node
;printf("生產者:%lu, 產品:%d\n", pthread_self(), node
->data
);sem_post(&custom
); sleep(1);}return NULL; }
void* custom_fun()
{while(1){sem_wait(&custom
); Node
* del
= phead
; phead
= phead
->next
; printf("消費者: %lu, 消費: %d\n", pthread_self(), del
->data
);free(del
); sem_post(&produce
); sleep(1);}return NULL; }
int main()
{srand(time(NULL));sem_init(&produce
, 0, 2);sem_init(&custom
, 0, 0);pthread_t p1
, p2
;pthread_create(&p1
, NULL, produce_fun
, NULL);pthread_create(&p2
, NULL, custom_fun
, NULL);pthread_join(p1
, NULL);pthread_join(p2
, NULL);sem_destroy(&produce
);sem_destroy(&custom
);return 0;
}
總結
以上是生活随笔為你收集整理的Linux学习之系统编程篇:使用信号量实现“生产者和消费者模型”的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。