简体   繁体   English

c ++ atomic vs lock

[英]c++ atomic vs lock

Suppose I have a class foo: 假设我有一个类foo:

class foo {
    static uint32 count_;
    pthread_mutex_t mu;

    void increase() {
      pthread_mutex_lock(&mu);
      count_++;
      pthread_mutex_unlock(&mu);
    }
}

Is there any difference if I don't use mutex, but just have a std::atomic as count_? 如果我不使用互斥锁,但是只有一个std :: atomic作为count_,有什么区别吗?

Thanks! 谢谢!

There is a huge difference. 这是个很大的差异。 pthread_mutex_lock can be very expensive, because it may incorporate a syscall*. pthread_mutex_lock可能非常昂贵,因为它可能包含一个系统调用*。 An atomic increment yields lock xadd . 原子增量产生lock xadd

Another advantage is that std::atomic<...> is maybe better portable, because it is part of the C++ standard. 另一个优点是std::atomic<...>可能更好的可移植性,因为它是C ++标准的一部分。 Pthread calls will most likely not work in Windows. Pthread调用很可能不适用于Windows。

*) To let the current thread sleep if the lock is already held by some other thread. *)如果某个其他线程已经持有锁,则让当前线程休眠。 But most likely only a spinlock will occur. 但很可能只会发生自旋锁

It is highly likely that the mutex lock is in fact implemented as an atomic increment in itself, and if you have the bad luck of getting contention on the lock, also involving a system call [assuming of course, that it isn't a system call either way!]. 事实上,互斥锁实际上很可能是作为一个原子增量实现的,并且如果你在锁上获得争用的运气不好,还涉及系统调用[假设当然,它不是一个系统无论如何都要打电话!]。

The atomic solution, on x86 will be a simple "lock add" operation. x86上的原子解决方案将是一个简单的“锁定添加”操作。 On other processors it may be more complex, but even so, the atomic is the minimum required for a mutex, so you have AT least that amount of work anyway. 在其他处理器上它可能更复杂,但即便如此,原子是互斥量所需的最小值,因此无论如何你至少要有这么多的工作量。

Then you add the mutex unlock, which may not be quite as complex, but it will not be completely free. 然后你添加互斥锁解锁,这可能不是那么复杂,但它不会完全免费。

So, yes, go for atomic. 所以,是的,去原子。

But like all things to do with performance, do measure a "before" and "after", to see that it actually does improve performance. 但是就像所有与性能有关的事情一样,请测量“之前”和“之后”,看看它确实提高了性能。

Note that I have seen someone explain that the original gnu C++ standard library implementation was actually done using some sort of mutex around the operation, but I believe if you have a reasonably recent version of g++ it should be fine (at least for x86 type processors). 请注意,我看到有人解释说原来的gnu C ++标准库实现实际上是使用某种互斥操作完成的,但我相信如果你有一个合理的最新版本的g ++它应该没问题(至少对于x86类型的处理器) )。 Microsoft has for a long time supported proper atomic operations as builtins, so should be fine there. 微软很长一段时间都支持内置的正确的原子操作,所以应该没问题。 Other processor architectures may vary. 其他处理器架构可能有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM