QMutex需要读取变量 [英] QMutex needed to read variable

查看:233
本文介绍了QMutex需要读取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过公共可访问成员变量来命令线程,这些成员变量通常受相应的互斥锁保护.

I command my threads via public accessible member variables that are usually protected by an according mutex.

我的问题是这样的: 如果在写访问期间单个变量受互斥锁保护 应该在读取访问期间也对其进行保护吗?还是我可以简单地读取它?

My question is this: If a single variable is protected by a mutex during write access should it also be protected during read access or can I simply read it?

示例:
线程检查是否应该做一些特别的事情
( doSpecial 写在另一个线程中)

Example:
A thread checks if something special should be done
(doSpecial is written in another thread)

// some code
if (doSpecial) {
  // code
}
// some code

此读取访问是否受互斥量保护?

Should this read access be protected by a mutex?

推荐答案

是的,如果在一个线程上修改了该变量,而在另一个线程上访问了该变量,则所有访问都必须由互斥对象保护.如果没有这种方法或某种其他同步方法,则不能保证修改是原子的(因此其他线程可能读取损坏的值),也不能保证其他线程会看到修改后的值(它可能保留在一个处理器的缓存中并且永远不会传播给他人).

Yes, if the variable is modified on one thread and accessed on others, then all accesses must be protected by the mutex. Without that, or some other synchronisation method, there is no guarantee that the modification is atomic (so other threads may read a corrupt value), nor that other threads will see the modified value (it may remain in the cache of one processor and never propagate to others).

在C ++ 11中,对于简单类型,您可以考虑使用std::atomic,而不是使用互斥锁保护的非原子变量.

In C++11, for simple types, you might consider std::atomic rather than a non-atomic variable protected by a mutex.

这篇关于QMutex需要读取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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