我需要互斥读取吗? [英] Do I need a mutex for reading?

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

问题描述

我有一个类有一个状态(一个简单的枚举),并从两个线程访问。对于改变状态我使用互斥(boost :: mutex)。是否可以安全地检查状态(例如compare state_ == ESTABLISHED)或者在这种情况下我也必须使用互斥?换句话说,当我只想读取一个可以由另一个线程同时写入的变量时,我需要互斥量。

I have a class that has a state (a simple enum) and that is accessed from two threads. For changing state I use a mutex (boost::mutex). Is it safe to check the state (e.g. compare state_ == ESTABLISHED) or do I have to use the mutex in this case too? In other words do I need the mutex when I just want to read a variable which could be concurrently written by another thread?

推荐答案

你有两个线程,他们交换信息,是你需要一个互斥,你可能还需要一个条件等待。

You have two threads, they exchange information, yes you need a mutex and you probably also need a conditional wait.

在你的例子中(compare state_ == ESTABLISHED)线程#2正在等待线程#1发起连接/状态。没有互斥量或条件/事件,线程#2必须持续轮询状态。

In your example (compare state_ == ESTABLISHED) indicates that thread #2 is waiting for thread #1 to initiate a connection/state. Without a mutex or conditionals/events, thread #2 has to poll the status continously.

线程用于提高性能(或提高响应能力),轮询通常导致减少性能,通过消耗大量的CPU或由于轮询间隔引入latencey。

Threads is used to increase performance (or improve responsiveness), polling usually results in decreased performance, either by consuming a lot of CPU or by introducing latencey due to the poll interval.

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

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