thatsme
thatsme

Reputation: 385

C++ Atomic/Mutex What way to follow?

I was wondering what is the better choice: it's assumed there is a trivially copyable object, let's say a queue data structure, that is used by several threads to pop/push data. The object provides only methods put/push, that can't be accessed by more than one thread the same time. Obviously if put is called, push can't be called neither.

Would you suggest to wrap the model into atomic type (if possible), or rather use mutexes?

Regards!

Upvotes: 1

Views: 322

Answers (2)

Ionut Neicu
Ionut Neicu

Reputation: 11

Atomic is hardware thing, whereas mutex is OS thing. Mutex will end up by suspending the task, even though in some cases mutex will behave as a spinlock for a short period of time aka "optimistic spin", see https://lore.kernel.org/all/[email protected]/T/ So, if you have small operations like incrementing a variable, aka "atomic", without waiting for other things which might take longer, then atomic is for you. If you want to (indefinitely) wait for some things to happen in other threads, polling for results via atomics, aka spinlock, might be a waste of CPU cycles therefore less cooperative, so it's better to use a mutex/condition variable which would suspend the task at a price of context switch latency.

Upvotes: 1

qeadz
qeadz

Reputation: 1516

Atomic is preferable for those kinds of cases. The atomic is a kind of operation supported by the CPU specifically whereas the other kinds of thread control tend to be implemented by the OS or other measures and incur more overhead.

EDIT: A quick search shows up this which has more info and is basically the same kind of question: Which is more efficient, basic mutex lock or atomic integer?

EDIT 2: And a more detailed article here http://www.informit.com/articles/article.aspx?p=1832575

Upvotes: 0

Related Questions