c++ - 用 atomic bool 同步 10 个线程
问题描述
我正在尝试使用 10 个线程,每个线程都需要打印他的号码,并且打印需要同步。我把它作为家庭作业,我必须使用原子变量来完成它(没有锁)。
这是我到目前为止所尝试的:
#include <atomic>
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
atomic<bool> turn = true;
void print(int i);
int main()
{
vector<thread> threads;
for (int i = 1; i <= 10; i++)
{
threads.push_back(thread(print, i));
}
for (int i = 0; i < 10; i++)
{
threads[i].join();
}
return 0;
}
void print(int i)
{
bool f = true;
for (int j = 0; j < 100; j++)
{
while((turn.compare_exchange_weak(f, false)) == false)
{ }
cout << i << endl;
turn = turn.exchange(true);
}
}
输出示例:
24
9143
541
2
8
预期输出:
2
4
9
1
4
3
1
5
4
10
8
解决方案
您在使用atomic
.
当 compare_exchange_weak 失败时,它将当前值存储在第一个参数中。如果您想继续尝试相同的值,则需要将其设置回原始值:
while ((turn.compare_exchange_weak(f, false)) == false)
{
f = true;
}
第二个问题是exchange
返回当前存储的值,因此:
turn = turn.exchange(true);
将 turn back 的值设置为 false,您只需要:
turn.exchange(true);
甚至只是:
turn = true;
在这种情况下,实际上不需要std::cout
同步,因为将为您进行同步,单个输出操作不会重叠,因此您只需将print
函数更改为以下内容,它就会正常工作:
void print(int i)
{
for (int j = 0; j < 100; j++)
{
cout << std::to_string(i) + "\n";
}
}
原子不是解决这个问题的正确方法,你的代码非常慢。互斥锁可能会更快。
推荐阅读
- java - Android Studio 4.2.1 更改我的图标后删除 mipmap 文件夹?
- javascript - D3 - . 根据子对象数组中是否存在项目过滤 selectAll
- windows - PowerShell 如何显示调用外部终端应用程序 (nssm.exe) 产生的输出字符串
- python - 想要在 Spacy 特征提取中打印特定数字
- python - 如何在具有可重复段落的指定字符串之后读取/修改具有特定位置的行?同时打印所有行
- azure-cosmosdb - 如何在 Azure Cosmos DB 模拟器中访问更改源
- cypress - cypress CLI 可以区分内部错误和一个失败的测试吗?
- shadow-dom - 有没有办法防止创建#shadow-root
- android - 可以使用 ndk 和 tcc 进行 android 应用程序开发吗?
- amazon-web-services - AWS ECS Fargate 蓝绿色部署 - 第二个目标组一直未能通过健康检查