【算法】两个线程交替打印0~100的数

文章对比了在C++中使用条件判断和条件变量进行多线程同步的方法。条件判断简单但可能增加CPU占用,而条件变量虽然复杂些,但在处理更复杂的任务时能降低CPU使用并提高效率。总结指出,在需要高效多线程同步的场景下,条件变量是更好的选择。
摘要由CSDN通过智能技术生成

方法一:条件判断

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

int main()
{
	int i = 0;

	thread t1([&i]()
		{
			while (i < 100)
			{
				if (i % 2)
				{
					cout <<"t1: " << this_thread::get_id() << " -> " << i << endl;
					++i;
				}
			}
		});

	thread t2([&i]()
		{
			while (i <= 100)
			{
				if (i % 2 == 0)
				{
					cout << "t2: " << this_thread::get_id() << " -> " << i << endl;
					++i;
				}
			}
		});

	t1.join();
	t2.join();

	return 0;
}

方法二:条件变量

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

int main()
{
	int i = 0;
	mutex mtx;
	condition_variable cv;

	thread t1([&]()
		{
			while (i < 100)
			{
				unique_lock<mutex> lock(mtx);
				while (i % 2 == 0)
				{
					cv.wait(lock);
				}

				cout << "t1: " << this_thread::get_id() << " -> " << i << endl;
				++i;

				cv.notify_one();
			}

		});

	thread t2([&]()
		{
			while (i < 100)
			{
				unique_lock<mutex> lock(mtx);
				while (i % 2)
				{
					cv.wait(lock);
				}

				cout << "t2: " << this_thread::get_id() << " -> " << i << endl;
				++i;

				cv.notify_one();
			}
		});

	t1.join();
	t2.join();

	return 0;
}

总结:条件变量相比于条件判断更加繁琐,但是使用条件变量对于CPU的占用更低,如果是执行更繁杂的多线程任务,使用条件变量效率更高。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AllinTome

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

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

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

打赏作者

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

抵扣说明:

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

余额充值