问题描述
我对并发还很陌生,但是在决定如何使用互斥体时遇到了麻烦.目前,它们散布在两个线程交互的我的代码中.这样使用互斥体是否合适?
I'm pretty new to concurrency, and I'm having trouble deciding on how to use mutexes. At the moment they are sprinkled all over my code where two threads interact. Would this use of mutexes be appropriate?
class Foo
{
public:
void SetMember(int n) { AcquireMutex(..); n_ = n; ReleaseMutex(...);}
private:
Thread()
{
while(1)
{
AcquireMutex(..);
// Do something with n_
ReleaseMutex(...);
}
}
};
我有很多数据成员可以通过不同的线程从外部读取和设置,而要跟踪所有互斥量的获取和释放,我感到很头疼.
I have quite a few data members that can be read and set from the outside by a different thread, and I'm finding it to be a headache to keep track of all the acquiring and releasing of mutexes.
推荐答案
不保证对基本类型的更改是线程安全的,或更确切地说,是原子的.实际上,如果您查看 <atomic>
,您会发现其中有几个专业化,包括std::atomic_int
.
Mutation of primitive types is not guaranteed to be thread safe, or more specifically atomic. In fact, if you look in <atomic>
you will notice that there are several specializations, including std::atomic_int
.
来自 cppreference
要专门回答有关互斥量使用的问题,可以,在您的示例中可以很好地使用互斥量.通常,您希望保持尽可能短的互斥量.换句话说,如果您有一个可以完成大量工作的函数,则只需将互斥锁锁定在非线程安全的代码周围,然后在代码成为线程安全的之后立即将其解锁.
To specifically answer your question about the use of mutexes, yes your use of mutexes is fine in your example. In general, you want to hold a mutex for as short as possible. In other words, if you have a function that does a lot of work, only lock the mutex around the un-threadsafe code, then unlock it as soon as the code is threadsafe afterwards.
这篇关于互斥量用于简单数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!