是否同时使用互斥锁 [英] Use mutex or not in a concurrent reading

查看:74
本文介绍了是否同时使用互斥锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Linux中使用C ++进行编程,并且正在使用pthreads库.我正在使用互斥锁来保护某些共享变量,但不确定在这种特定情况下是否有必要使用互斥锁.

I am programming in C++ in Linux and I am using pthreads library. I am using mutex to protect some shared variables but I am not sure if in this specific case it is necessary the use of mutex.

我有3个线程.共享变量是字符串(全局变量).

I have 3 threads. The shared variable is a string (global variable).

Thread1更改它的值,然后,thread2和thread3读取它的值并存储在另一个字符串中.

Thread1 changes it's value and afterwards, thread2 and thread3 read it's value and store in another string.

在这种情况下,字符串的值只能由一个线程修改.仍然有必要使用互斥锁来保护两个线程并发读取时的共享变量吗?

In this case, the string's value is only modified by one thread. Is still necessary the use of mutex to protect a shared variable in a concurrent read by two threads?

推荐答案

"Thread1更改了它的值,然后..."-如果"afterwards"表示其他线程是在创建后创建的更改,无需互斥;线程创建会同步内存.如果还有其他含义,则您需要某种形式的同步,部分原因是如果没有同步,则不同线程中的事后"就毫无意义.

"Thread1 changes it's value and afterwards ..." -- if "afterwards" means that the other threads are created after the change, there's no need for a mutex; thread creation synchronizes memory. If it means anything else then you need some form of synchronization, in part because "afterwards" in different threads is meaningless without synchronization.

这篇关于是否同时使用互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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