在主线程和工作线程之间读/写入变量

发布于 2025-02-09 18:57:39 字数 170 浏览 2 评论 0原文

在多线程C ++桌面应用程序中,如果主线程具有主循环:

  • 它读取/写入变量,然后
  • 调用读取/写入该变量的线程,

如果该变量之间需要同步,则需要同步主线程和工作线程永远不会同时发生?那就是主线程读/写入变量,调用线程,然后等待线程完成,然后再读取/编写变量。

In a multi-threaded C++ desktop application, if the main thread has a main loop where:

  • It reads/write to a variable and then
  • Invokes thread that reads/writes to that variable

Does that variable need to be synchronized if the reading/writing between the main thread and the worker thread never happens at the same time? That is the main thread reads/writes to the variable, invokes the thread(s), then waits for the threads to complete before reading/writing the variable again.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画离情绘悲伤 2025-02-16 18:57:39

注意:下面的答案假定工作线程是由主线程创建并连接的(事实证明是错误的 - 请参见下面的更新)。


如果您确定主线程在启动工作线程之前正在访问共享数据,并且仅在加入工作工作线程时才会访问它,
然后,您不需要同步。

这是因为创建一个新线程(并且加入 it)是为创建同步屏障而进行的。

这意味着新线程将可见主线程所做的更改。当完成新线程并连接时,主线程将看到它的更改。

您可以在此问题的答案中查看更多信息:产卵线程是否可以单独提供内存订单?


更新:
如您在OP的评论中所看到的,以下,实际上并未创建一个新线程。使用线程池的库。在这种情况下,同步的需求取决于库的实现。
如果您不确定这一点 - 您最好使用同步机制。

Note: the answer below assumed the worker thread is created and joined by the main thread (this turned out to be false - see the update below).


If you are sure that the main thread is accessing the shared data before the worker thread is launched, and will access it later only when the worker thread is joined,
then you don't need to synchronize.

This is because creating a new thread (and joining it) is guarenteed to create a synchronization barrier.
It means that the changes done by the main thread will be visible to the new thread. And when the new thread is done and was joined, the changes it did will be visible to the main thread.

You can see more info in the answer to this question: Does spawning a thread provide memory order guarantees on its own?.


Update:
As you can see in the OP's comment below, a new threads is not actually created. A library using a thread pool is used instead. In this case the need for synchronization is dependent on the library's implementation.
If you are not sure about it - you'd better use a synchronization mechanism.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文