/*
*mutex=1;
*lock mutex=0;
*unlock mutex=1;
*車位:共享資源 [管理員:互斥鎖:串行---信號量:並行 ]車:線程
*互斥鎖:每次只能夠放一輛車
*信號量:可以運行多個線程同時訪問共享資源
*sem_init();
*sem_wait();===
*sem_post(sem,**)//解鎖
*/
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
sem_t produce_sem;
sem_t consume_sem;
//線程同步
pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
typedef struct node
{
int data;
struct node *next;
}Node;
//指針
Node *head=NULL;
/*
producer:
consumer:
*/
void *consumer(void *arc){
while(1){
sem_wait(&consume_sem);//初始化爲0則阻塞
//阻塞到post時候進行喚醒
//吃東西訪問共享數據刪除節點
Node *pdel= head;
head = head->next;
printf("-------consumer:%#X spend %d\n",pthread_self(),pdel->data);
free(pdel);
//將佔有的資源還給生產者???
sem_post(&produce_sem);//++
sleep(rand()% 3);
}
pthread_exit((void *)0);
}
void *producer(void *arc){
while(1){
sem_wait(&produce_sem);//相當於資源--
//創建節點
Node *pnew =(Node *)malloc(sizeof(Node));
//插入節點初始化
pnew->data = rand() % 1000; //0-999
//頭插法
pnew->next = head;
head = pnew;
printf("-------producer:%#X produce %d\n",pthread_self(),pnew->data);
pthread_mutex_unlock(&mylock);
//通知消費者喚醒一個線程
sem_post(&consume_sem);//++
//pthread_cond_broadcast(&cond);//喚醒所有線程
// pthread_cond_signal(&cond);
//printf("lmj\n");
sleep(rand()%3);
}
//通知消費者
pthread_exit((void *)1);
}
int main(int argc, char const *argv[])
{
pthread_t tid1,tid2;
//消費者資源爲0
sem_init(&consume_sem,0,0);
sem_init(&produce_sem,0,4);//最多5個
pthread_create(&tid1,NULL,producer,NULL);
pthread_create(&tid2,NULL,consumer,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destory(consume_sem);
sem_destory(&produce_sem)
//sleep(10);
return 0;
}
信號量對比互斥鎖實現生產者消費者模型Linux C語言
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.