是否有必要为只读线程和只写线程创建互斥锁? [英] Is is necessary to create a Mutex for a read-only thread and a write-only thread?

查看:42
本文介绍了是否有必要为只读线程和只写线程创建互斥锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有2个线程,一个只读取信号,另一个只设置信号.

There are 2 threads,one only reads the signal,the other only sets the signal.

是否需要为signal创建互斥锁以及原因?

Is it necessary to create a mutex for signal and the reason?

更新

我只关心如果两个线程同时读取/设置它是否会崩溃

All I care is whether it'll crash if two threads read/set the same time

推荐答案

您可能希望为此使用原子变量,尽管互斥锁也可以.

You will probably want to use atomic variables for this, though a mutex would work as well.

问题是无法保证数据在线程之间保持同步,但使用原子变量可确保一旦一个线程更新该变量,其他线程立即读取其更新值.

The problem is that there is no guarantee that data will stay in sync between threads, but using atomic variables ensures that as soon as one thread updates that variable, other threads immediately read its updated value.

如果一个线程更新缓存中的变量,而第二个线程从内存中读取变量,则可能会出现问题.如果缓存尚未刷新到内存,第二个线程将读取该变量的过时值.原子变量确保变量的值跨线程一致.

A problem could occur if one thread updates the variable in cache, and a second thread reads the variable from memory. That second thread would read an out-of-date value for the variable, if the cache had not yet been flushed to memory. Atomic variables ensure that the value of the variable is consistent across threads.

如果您不关心及时的变量更新,您可以使用单个 volatile 变量.

If you are not concerned with timely variable updates, you may be able to get away with a single volatile variable.

这篇关于是否有必要为只读线程和只写线程创建互斥锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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