9

I know, that in some situations you can avoid having to lock mutexes (std::mutex) by using std::atomic, thus increasing performance.

Can you name a situation like this, and preferably show some example code on how to do this (how do you use std::atomic)?

Also, when I lock a mutex, the performance degrades because other threads are unable to continue doing their work for the period of time the mutex is locked. Is this the only issue with a mutex? I mean, is locking/unlocking a mutex an expensive operation or it's just about what I mentioned above?

krispet krispet
  • 1,648
  • 1
  • 14
  • 25
  • Do you understand the notion of an atomic operation? If you do, then you'll see that if you can ensure that an operation is atomic, there is no need to guard such an operation with a mutex. – Cory Kramer Jun 15 '15 at 14:18
  • Edited to make it narrower, hope it clears the question. – krispet krispet Jun 15 '15 at 15:44
  • Try taking a look through [this post](https://stackoverflow.com/questions/9553591/c-stdatomic-what-is-stdmemory-order-and-how-to-use-them). If you haven't already I would strongly suggest reading [C++ Concurrency In Action](http://www.amazon.com/C-Concurrency-Action-Practical-Multithreading/dp/1933988770). The [author](https://stackoverflow.com/users/5597/anthony-williams) was one of the primary maintainers of [`boost::Thread`](http://www.boost.org/users/people/anthony_williams.html). They have a whole chapter (chpt 5) on the C++ memory model, and atomic types. – Cory Kramer Jun 15 '15 at 16:50
  • Also see [here](https://stackoverflow.com/questions/7461484/memory-model-ordering-and-visibility/7463092#7463092) – Cory Kramer Jun 15 '15 at 16:55
  • Since this question still pops up out of the few related, I offer as an example a shared mutex / shared lock code based on atomic and memory ordering that I wrote after studying this subject a little. https://github.com/shutow/shared_mutex – Vladimir Shutow Mar 28 '18 at 16:26

0 Answers0