多个线程可以同时安全地将相同的值写入相同的变量吗? [英] Can multiple threads write the same value to the same variable at the same time safely?

查看:54
本文介绍了多个线程可以同时安全地将相同的值写入相同的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多个线程可以同时安全地将相同的值写入相同的变量吗?

Can multiple threads write the same value to the same variable at the same time safely?

对于特定示例—下面的代码由C ++标准保证可以在每个符合标准的系统上编译,运行时没有未定义的行为并显示"true"吗?

For a specific example — is the below code guaranteed by the C++ standard to compile, run without undefined behavior and print "true", on every conforming system?

#include <cstdio>
#include <thread>

int main()
{
    bool x = false;
    std::thread one{[&]{ x = true; }};
    std::thread two{[&]{ x = true; }};
    one.join();
    two.join();
    std::printf(x ? "true" : "false");
}

这是一个理论问题;我想知道它是否一定总是有效,而不是在实践中是否有效(或者编写这样的代码是否是一个好主意:)).如果有人可以指出标准的相关部分,我将不胜感激.以我的经验,它总是可以在实践中起作用,但是我不知道它是否一定能起作用,而是我总是使用 std :: atomic -我想知道在这种情况下这是否绝对必要.

This is a theoretical question; I want to know whether it definitely always works rather than whether it works in practice (or whether writing code like this is a good idea :)). I'd appreciate if someone could point to the relevant part of the standard. In my experience it always works in practice, but not knowing whether or not it's guaranteed to work I always use std::atomic instead - I'd like to know whether that's strictly necessary for this specific case.

推荐答案

否.

您需要通过使用互斥锁或使它们原子化来同步对这些变量的访问.

You need to synchronize access to those variables, either by using mutexes or by making them atomic.

写入相同值时没有豁免.您不知道编写该值涉及哪些步骤(这是潜在的实际问题),也不知道代码为何具有未定义行为的标准.这意味着您的编译器可以使程序完全混乱(这是您需要避免的 real 问题).

There is no exemption for when the same value is being written. You don't know what steps are involved in writing that value (which is the underlying practical concern), and neither does the standard which is why code has undefined behaviour … which means your compiler can just make absolute mayhem with your program (and that's the real issue you need to avoid).

有人会告诉你,这样的架构可以保证对这些大小的变量进行原子写入.但这并不会改变UB方面.

Someone's going to come along and tell you that such-and-such an architecture guarantees atomic writes to these sized variables. But that doesn't change the UB aspect.

您要查找的段落是:

[intro.races/2] :如果两个表达式求值之一修改了一个内存位置([intro.memory]),而另一个表达式读取或修改了同一个内存位置,则两个表达式求值 conflict .

[intro.races/21] :[…]如果程序的执行包含两个潜在的并发冲突动作[…],则该执行包含数据争用.任何此类数据争用都会导致未定义的行为.

[intro.races/21]: […] The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, […]. Any such data race results in undefined behavior.

…和周围的措辞.该部分实际上是很深奥的,但是您真的不需要解析它,因为这是经典的教科书数据竞赛,您可以在任何有关编程的书中阅读.

… and the surrounding wording. That section is actually quite esoteric, but you don't really need to parse it as this is a classic, textbook data race that you can read about in any book on programming.

这篇关于多个线程可以同时安全地将相同的值写入相同的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆