#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <iostream>
using namespace std;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;//初始构造条件变量
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;//初始构造锁
pthread_t tid1,tid2,tid3;
int x=10;
int y=20;
void*thrd_1(void*arg)
{
pthread_mutex_lock(&qlock);
printf("jiangxin before the pthread_cond_wait\n");
pthread_cond_wait(&qready,&qlock); //个函数在qready条件没满足的时候会卡在这里,并且,会把传入的互斥锁解锁,为什么要解锁的,拟可以想想,
//如果不解锁的话,那外部就没有可以对x,y的修改权,应为其他两个线程想要修改这两个值的话都需要对qclock进行枷锁
printf("jiangxin after the pthread_cond_wait\n");
pthread_mutex_unlock(&qlock);
cout<<"thread 1"<<endl;
}
void*thrd_2(void*arg)
{
pthread_mutex_lock(&qlock);
x=20;
y=10;
cout<<"has change x and y"<<endl;
pthread_mutex_unlock(&qlock);
if(x>y)
{
printf("jiangxin the x is bigger than y\n");
pthread_cond_signal(&qready);
}
cout<<"thread 2"<<endl;
}
void*thrd_3(void*arg)
{
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
cout<<"thread 3"<<endl;
}
int main(int argc,char**argv)
{
int err;
err = pthread_create(&tid1,NULL,thrd_1,NULL);
if(err!=0)
{
cout<<"pthread1 create error"<<endl;
}
err = pthread_create(&tid2,NULL,thrd_2,NULL);
if(err!=0)
{
cout<<"pthread2 create error"<<endl;
}
err = pthread_create(&tid3,NULL,thrd_3,NULL);
if(err!=0)
{
cout<<"pthread3 create error"<<endl;
}
while(1)
{
sleep(1);
}
return 0;
}
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <iostream>
using namespace std;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;//初始构造条件变量
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;//初始构造锁
pthread_t tid1,tid2,tid3;
int x=10;
int y=20;
void*thrd_1(void*arg)
{
pthread_mutex_lock(&qlock);
printf("jiangxin before the pthread_cond_wait\n");
pthread_cond_wait(&qready,&qlock); //个函数在qready条件没满足的时候会卡在这里,并且,会把传入的互斥锁解锁,为什么要解锁的,拟可以想想,
//如果不解锁的话,那外部就没有可以对x,y的修改权,应为其他两个线程想要修改这两个值的话都需要对qclock进行枷锁
printf("jiangxin after the pthread_cond_wait\n");
pthread_mutex_unlock(&qlock);
cout<<"thread 1"<<endl;
}
void*thrd_2(void*arg)
{
pthread_mutex_lock(&qlock);
x=20;
y=10;
cout<<"has change x and y"<<endl;
pthread_mutex_unlock(&qlock);
if(x>y)
{
printf("jiangxin the x is bigger than y\n");
pthread_cond_signal(&qready);
}
cout<<"thread 2"<<endl;
}
void*thrd_3(void*arg)
{
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
cout<<"thread 3"<<endl;
}
int main(int argc,char**argv)
{
int err;
err = pthread_create(&tid1,NULL,thrd_1,NULL);
if(err!=0)
{
cout<<"pthread1 create error"<<endl;
}
err = pthread_create(&tid2,NULL,thrd_2,NULL);
if(err!=0)
{
cout<<"pthread2 create error"<<endl;
}
err = pthread_create(&tid3,NULL,thrd_3,NULL);
if(err!=0)
{
cout<<"pthread3 create error"<<endl;
}
while(1)
{
sleep(1);
}
return 0;
}
本文介绍了一个使用C++实现的多线程示例,通过条件变量和互斥锁协调线程之间的执行顺序。主要展示了如何利用pthread库中的pthread_cond_wait和pthread_cond_signal函数来控制线程等待特定条件及通知条件变化。
3265

被折叠的 条评论
为什么被折叠?



