互斥锁,条件变量实现:
1 #include<stdio.h>
2 #include<sys/wait.h>
3 #include<unistd.h>
4 #include<stdlib.h>
5 #include<sys/types.h>
6 #include<sys/stat.h>
7 #include<string.h>
8 #include<sys/socket.h>
9 //#include<iostream>
10 #include<fcntl.h>
11 #include<sys/mman.h>
12 #include<pthread.h>
13 #include<signal.h>
14
15 //using namespace std;
16
17 //创建一个节点的结构
18 typedef struct node
19 {
20 int data;
21 struct node*next;
22 }Node;
23
24 //先定义出来一个头指针
25 Node* head = NULL;
26
27 //线程同步需要条件锁,互斥锁
28 pthread_mutex_t mutex;
29 pthread_cond_t cond;
30
31
32 void * producer(void * arg){
33 while(1){
34 Node* p = (Node*)malloc(sizeof(Node));
35 //节点的初始化
36 p->data = rand()%1000;//0~99
37
38 //使用胡吃锁保护共享数据
39 pthread_mutex_lock(&mutex);
//指针域
42 p->next = head;
43 head = p;
44 //cout<<"chuang jian :"<<pthread_self()<<p->data<<endl;
45 printf("chuang jian :%lu, data :%d \n",pthread_self(),p ->data);
46
47 pthread_mutex_unlock(&mutex);
48
49 //通知阻塞的消费者线程,解除阻塞
50 pthread_cond_signal(&cond);
51
52 sleep(rand()%3);
53 }
54 return NULL;
55 }
56
57 void customer(void * arg){
58 while(1){
59
60 pthread_mutex_lock(&mutex);
61
62 //判断链表是否为空
63 if(head == NULL){
64 //线程阻塞色-对胡吃锁解锁
65 pthread_cond_wait(&cond,&mutex);
66 //解除则色之后,会对胡吃锁在做枷锁
67 }
68
69 //链表不为空,删除一个节点
70 Node* pdel = head;
71 head = head->next;
72 //cout<<"shan chu :"<<pthread_self()<<pdel->data<<endl;
73 printf("xiao fei :%lu, data :%d \n",pthread_self(),pdel ->data);
74 free(pdel);
75 pthread_mutex_unlock(&mutex);
76 }
77 return NULL;
}
int main(int argc,const char* argv[]){
81
82 //创建生产者线程:
83 pthread_mutex_init(&mutex,NULL);
84 pthread_cond_init(&cond,NULL);
85
86
87 pthread_t p1;
88 pthread_t p2;
89
90 pthread_create(&p1,NULL,producer,NULL);
91 //创建消费者线程
92 pthread_create(&p2,NULL,customer,NULL);
93
94 //阻塞回收
95 pthread_join(&p1,NULL);
96 pthread_join(&p2,NULL);
97
98 pthread_mutex_destroy(&mutex);
99 pthread_cond_destroy(&cond);
100
101 return 0;
102 }
2、信号量实现消费者,生产者模型
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>
sem_t producer_sem;
sem_t customer_sem;
typedef struct node{
int data;
struct node* next;
}Node;
Node* head = NULL;
void * producer(void* arg){
while(1){
sem_wait(&producer_sem);
Node* node = (Node*)malloc(sizeof(Node));
node->data = rand()%1000;
node->next = head;
head = node;
printf("+++ 生产者:%lu, %d \n",pthread_self(),node->data);
sem_post(&customer_sem);
sleep(rand()%5);
}
}
void* customer(void* arg){
while(2){
sem_wait(&customer_sem);
Node * pdel = head;
head = head->next;
printf("----消费者:%lu , %d \n",pthread_self(),pdel->data);
free(pdel);
sem_post(&producer_sem);
sleep(rand()%5);
}
}
int main(int argc,char* argv[]){
pthread_t p1;
pthread_t p2;
sem_init(&producer_sem,0,4);
sem_init(&customer_sem,0,0);
pthread_create(&p1,NULL,producer,NULL);
pthread_create(&p2,NULL,customer,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
sem_destroy(&producer_sem);
sem_destroy(&customer_sem);
return 0;
}