c++ - 为什么这不是线程安全的?
问题描述
为什么这不是线程安全的?据我了解,结果应该是一串100
s。
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
int main()
{
std::vector<int*> values(100, new int(0));
std::vector<std::thread> threads;
std::vector<std::mutex> mutexes(100);
for (int i = 0; i < 100; i++)
{
threads.emplace_back([](int* v, std::mutex* m)
{
for (int j = 0; j < 100; j++)
{
std::lock_guard<std::mutex> guard(*m);
(*v)++;
}
}, values[i], &mutexes[i]);
}
for (auto& t : threads) t.join();
for (int i = 0; i < 100; i++)
{
std::lock_guard<std::mutex> guard(mutexes[i]);
std::cout << (*(values[i])) << ' ';
}
std::cout << std::endl;
}
结果:
9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863 9863
解决方案
您只需要一个互斥锁。对于 100 个互斥锁,每个线程将立即锁定自己的互斥锁,而不是等待其他线程,因此不会发生同步。
推荐阅读
- javascript - 如何使用 React 中的 Hooks 在带有汉堡菜单的标题中切换侧边栏组件
- liferay - Liferay portal-ext.properties 文件中启用的语言设置似乎不起作用
- python - Python:YYYY-MM-DDTHH:MM:SS 的 date.time strptime 格式?
- exception - 构建 Xamarin.iOS 时没有名为“NFCVASReaderSessionDelegate”的类型或协议
- upgrade - 超集从 0.38 升级到 1.0.1
- javafx - 将程序导出到 jar 文件时,JFXDatePicker 不起作用
- ansible - 如何在 AWX 中为库存脚本存储和检索秘密?
- node.js - 如何使用 http-proxy 和 Harmonon 将脚本标记注入 HTML 正文
- django - Django Rest-Framework-Simplejwt 不适用于 modheader
- python - 感知器神经网络不会学习特定范围内的值