C++|C++ 3个线程顺序输出1-9
3个线程,顺序输出123456789
#include
#include
#include
#include
#include
#include
using namespace std;
int g_num = 0;
mutex myMutex;
condition_variable cv1, cv2, cv3;
void thread_Func1()
{
int a = 0;
while (true)
{
a = -1;
{
unique_lockguard(myMutex);
{
while (a % 3 != 1 || a == - 1)
{
cv1.wait(guard);
a = g_num;
}
}
}
cout << " thread_id : " << std::this_thread::get_id() << " g_numer : " <guard(myMutex);
{
while (a % 3 != 2 || a == -1)
{
cv2.wait(guard);
a = g_num;
}
}
}
cout << " thread_id : " << std::this_thread::get_id() << " g_numer : " << a << endl;
if (a == 8)
break;
}
}void thread_Func3()
{
int a = 0;
while (true)
{
a = -1;
{
unique_lockguard(myMutex);
{
while (a % 3 != 0 || a == -1 )
{
cv3.wait(guard);
a = g_num;
}
}
}
cout << " thread_id : " << std::this_thread::get_id() <<" g_numer : " << a << endl;
if (a == 9)
break;
}
}
void thread_ctl()
{
int a = 0;
while (a < 9)
{
{
unique_lockguard(myMutex);
a = ++g_num;
}
if (a % 3 == 1)
cv1.notify_one();
else if (a % 3 == 2)
cv2.notify_one();
else
cv3.notify_one();
Sleep(1000);
}
}int main()
{
std::thread threadFunc1(thread_Func1);
std::thread threadFunc2(thread_Func2);
std::thread threadFunc3(thread_Func3);
std::thread threadCtl(thread_ctl);
threadFunc1.join();
threadFunc2.join();
threadFunc3.join();
threadCtl.join();
return 0;
}
【C++|C++ 3个线程顺序输出1-9】
文章图片
推荐阅读
- opencv|opencv C++模板匹配的简单实现
- Linux下面如何查看tomcat已经使用多少线程
- C语言学习|第十一届蓝桥杯省赛 大学B组 C/C++ 第一场
- 多线程NSOperation
- c++基础概念笔记
- 普通人通往大神的3个创作路径
- spring|spring boot中设置异步请求默认使用的线程池
- Android中非UI主线程能不能操作UI()
- 牛逼!C++开发的穿越丛林真人游戏,游戏未上线就有百万人气
- 2020-02-27人情世故的63个定律!