C++11 用三个线程按顺序输出数字

文章介绍了如何使用C++的条件变量、mutex和线程来控制三个线程按照3的倍数余数顺序输出,展示了notify_one和notify_all在多线程同步中的应用。
摘要由CSDN通过智能技术生成

使用条件变量控制三个线程输出数据,
第一个线程输出3的倍数余1,
第二个线程输出3的倍数余2,
第三个线程输出3的倍数


#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

mutex g_mutex;
condition_variable g_conV;
void thread_1_func(int& i);
void thread_2_func(int& i);
void thread_3_func(int& i);
int main()
{
	int i = 1;
	thread thread_1(thread_1_func, ref(i));
	thread thread_2(thread_2_func, ref(i));
	thread thread_3(thread_3_func, ref(i));

	thread_1.join();
	thread_2.join();
	thread_3.join();
}

void thread_1_func(int& i)
{
	while (true)
	{
		// 这个线程运行一次
		cout << "thread_1 running ..." << i << endl;

		unique_lock<mutex> lock(g_mutex);
		g_conV.wait(lock, [&i]() {return i % 3 == 1; });	// 当某个i处于99 的时候,这个肯定处于wait状态,wait的那个线程会输出100
		cout << "thread_1 " << i << endl;
		i++;

		if (i > 100) return;	// 达到100之后,就不用notify了,不用通知其他的县线程了

		g_conV.notify_one();
	}
}

void thread_2_func(int& i)
{
	while (true)
	{
		// 这个线程运行一次
		cout << "thread_2 running ..." << i << endl;
		unique_lock<mutex> lock(g_mutex);
		g_conV.wait(lock, [&i]() {return i % 3 == 2; });	// 当某个i处于99 的时候,这个肯定处于wait状态,wait的那个线程会输出100
		cout << "thread_2 " << i << endl;
		i++;

		if (i > 100) return;	// 达到100之后,就不用notify了,不用通知其他的县线程了

		g_conV.notify_one();
	}
}

void thread_3_func(int& i)
{
	while (true)
	{
		// 这个线程运行一次
		cout << "thread_3 running ..." << i << endl;

		unique_lock<mutex> lock(g_mutex);
		g_conV.wait(lock, [&i]() {return i % 3 == 0; });  // 当某个i处于99 的时候,这个肯定处于wait状态,wait的那个线程会输出100
		cout << "thread_3 " << i << endl;
		i++;

		if (i > 100) return;  // 达到100之后,就不用notify了,不用通知其他的县线程了

		g_conV.notify_one();
	}
}

 

条件变量中的notifyOne和notifyAll是线程间通信的方法。

notifyOne是唤醒等待在该条件变量上的一个线程。如果有多个线程在该条件变量上等待,那么只会唤醒其中一个线程。具体哪个线程被唤醒是由操作系统决定的。

notifyAll是唤醒等待在该条件变量上的所有线程。如果有多个线程在该条件变量上等待,那么所有线程都会被唤醒。

notifyOne和notifyAll的使用场景取决于具体的需求。当只需要唤醒一个线程时,可以使用notifyOne。而当需要唤醒所有等待的线程时,可以使用notifyAll。

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张亚成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值