#include <cstdio>
#include<pthread.h>
#include <iostream>
#include<unistd.h>
#include<string.h>
using namespace std;
//节点结构
typedef struct node {
int data;
struct node* next;
}Node;
//永远指向链表头部的指针
Node *head = NULL;
//线程同步-互斥锁
pthread_mutex_t mutex;
//条件变量-阻塞线程
pthread_cond_t cond;
//生产者
void* producer(void *arg) {
while (1) {
Node* p = new Node;
//Node * p = (Node*)malloc(sizeof(Node));
p->data = rand() % 1000;
pthread_mutex_lock(&mutex);
p->next = head;
head = p;
cout << "====produce:" << pthread_self() << " " << p->data << endl;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
sleep(rand() % 3);
}
return NULL;
}
void* customer(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (head == NULL) {
pthread_cond_wait(&cond, &mutex);
}
Node* pdel = head;
head = head->next;
cout << "--------customer: " << pthread_self() << " " << pdel->data << endl;
delete pdel;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
pthread_t p1, p2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
//创建生产者线程
pthread_create(&p1, NULL, producer, NULL);
//创建消费者线程
pthread_create(&p2, NULL, customer, NULL);
//阻塞回收子线程
pthread_join(p1, NULL);
pthread_join(p2, NULL);
return 0;
}
Linux 线程-条件变量
最新推荐文章于 2024-04-15 09:15:02 发布