#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
pthread_cond_t cond=PTHREAD_COND_INITIALIZER; //初始化条件变量
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//静态初始化互斥锁
struct msg //公共代码区
{
int num;
struct msg* next;
};
struct msg* head;//定义头节点
void* produse(void* arg)
{
while (1)
{
struct msg* mp=(struct msg*)malloc(sizeof(struct msg));//申请空间
mp->num=rand()%1000; //随机产生0-999的数值,并初始化公共代码区
printf("produse:%d\n",mp->num);
pthread_mutex_lock(&mutex);
mp->next=head; //head是一个空指针,将next赋值
head=mp; //将mp赋值给head这个空指针,唤醒改变consumer条件变量
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);//唤醒在条件变量上阻塞的线程
sleep(rand()%3); //随机睡眠0-3秒,为了方便观察
}
return nullptr;
}
void* consumer(void* arg)
{
while (1)
{
struct msg* mp;
pthread_mutex_lock(&mutex);//加锁
while (head==nullptr)
{
pthread_cond_wait(&cond,&mutex);//阻塞等待条件变量,并解锁,等待被唤醒
}
mp=head; //将head赋值给结构体mp
head=mp->next; //然后将其置为空
pthread_mutex_unlock(&mutex);//解锁
printf("consumer======>>%d\n",mp->num);
free(mp); //释放之前申请的内存空间
sleep(rand()%3);//随机睡眠方便观察
}
return nullptr;
}
int main(int argc, char const *argv[])
{
pthread_t t1,t2; //定义线程
srand(time(nullptr));//随机数种子
pthread_create(&t1,nullptr,&produse,nullptr);//创建线程,循环创建多个线程可以用数组
pthread_create(&t2,nullptr,&consumer,nullptr);
pthread_join(t1,nullptr);//释放线程
pthread_join(t2,nullptr);
return 0;
}
输出结果:
kali@kali:~/code$ g++ 1.cpp -lpthread
kali@kali:~/code$ ./a.out
produse:399
consumer======>>399
produse:807
consumer======>>807
produse:92
produse:956
consumer======>>956
produse:347
produse:46
produse:212
consumer======>>212
produse:705
consumer======>>705
produse:255
consumer======>>255
produse:127
consumer======>>127
produse:211
produse:639
consumer======>>639
produse:274
consumer======>>274
produse:674
consumer======>>674
produse:633
consumer======>>633
produse:966
consumer======>>966
produse:13
consumer======>>13
produse:82
consumer======>>82
produse:751
consumer======>>751
produse:922
produse:713
consumer======>>713
produse:925
consumer======>>925
consumer======>>922
produse:774
consumer======>>774
produse:418
produse:107
produse:727
produse:73
consumer======>>73
produse:134
produse:814
produse:493
produse:442
^C
kali@kali:~/code$