方法一:条件判断
#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的占用更低,如果是执行更繁杂的多线程任务,使用条件变量效率更高。文章来源地址https://www.toymoban.com/news/detail-628600.html
文章来源:https://www.toymoban.com/news/detail-628600.html
到了这里,关于【算法】两个线程交替打印0~100的数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!