在多线程C ++应用程序中,我是否需要互斥体来保护简单的布尔值? [英] In a multi-threaded C++ app, do I need a mutex to protect a simple boolean?

查看:78
本文介绍了在多线程C ++应用程序中,我是否需要互斥体来保护简单的布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程C ++应用程序,它使用OpenSceneGraph库进行3D渲染.我计划使用boost :: threads作为一个单独的线程启动OSG的渲染循环,将包含共享状态的数据结构传递给该线程.我正在尝试避免太重的内容(例如互斥体)进行同步,因为渲染循环需要非常紧密,而OSG本身则试图避免必须锁定.大多数共享状态是在线程启动之前设置的,并且从未更改.我确实有一些需要更改的数据,我打算对它们进行双缓冲.但是,我有一个简单的布尔值,用于发信号通知线程暂停渲染,然后恢复渲染,并杀死线程.在这两种情况下,应用程序线程都会设置布尔值,而渲染线程只会读取它.我需要同步访问这些布尔值吗?据我所知,可能发生的最糟糕的事情是渲染循环在暂停或退出之前继续运行一个额外的帧.

I have a multi-threaded C++ app which does 3D rendering with the OpenSceneGraph library. I'm planning to kick off OSG's render loop as a separate thread using boost::threads, passing a data structure containing shared state in to the thread. I'm trying to avoid anything too heavyweight (like mutexes) for synchronization, as the render loop needs to be pretty tight, and OSG itself tries to avoid having to ever lock. Most of the shared state is set before the thread is started, and never changed. I do have some data that does need to be changed, which I am planning to double-buffer. However, I have a simple boolean for signaling the thread to suspend rendering, and later resume rendering, and another to kill it. In both cases the app thread sets the bool, and the render thread only reads it. Do I need to synchronize access to these bools? As far as I can tell, the worse thing that could happen is the the render loop continues on for an extra frame before suspending or quitting.

推荐答案

在具有标准定义的并发性的C ++ 11和更高版本中,请使用std::atomic<bool>来实现此目的.来自 http://en.cppreference.com/w/cpp/atomic/atomic:

In C++11 and later, which has standards-defined concurrency, use std::atomic<bool> for this purpose. From http://en.cppreference.com/w/cpp/atomic/atomic:

如果一个线程写入一个原子对象,而另一个线程读取一个原子对象,则该行为是明确定义的(有关数据竞争的详细信息,请参阅内存模型).

If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).


对于某些编译器和某些操作环境,以下旧答案在过去的某个时候可能是正确的,但今天不应该依赖它:


The following old answer may have been true at some time in the past with some compilers and some operating environments, but it should not be relied upon today:

您是正确的,在这种情况下,您不需要同步布尔值.不过,您应该声明它们volatile,以确保编译器每次实际上都从内存中读取它们,而不是将先前的读取缓存在线程中(这是一个简化的解释,但为此目的应该这样做).

You're right, in this case you won't need to synchronise the bools. You should declare them volatile though, to ensure that the compiler actually reads them from memory each time, instead of caching the previous read in a thread (that's a simplified explanation, but it should do for this purpose).

以下问题对此有更多信息: C ++线程,共享数据

The following question has more information about this: C++ Thread, shared data

这篇关于在多线程C ++应用程序中,我是否需要互斥体来保护简单的布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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