I’ve been dealing with threads for past two weeks or so and I want to ask question about threads.
I’ve never dealt with a single mutex altough I know about them. Why? Because I use very simple boolean switches like here (C++, example thread):
bool fakeMutex = false;
...
while (fakeMutex);
fakeMutex = true;
// do smth
fakeMutex = false;
I’ve been thinking about this and I started believing there’s a very tiny (yet I believe possible chance) it can fail.
Given that in assembly these theorically should look something like this:
Compare:
CMP 0,[offset fakeMutex]
JG Compare
MOV [offset fakeMutex],1
; do smth
MOV [offset fakeMutex],0
The only way this mutex can fail is if CMP 0,[offset fakeMutex] executes while fakeMutex is false and then right after that another thread takes over, goes after MOV [offset fakeMutex],1 and then OLD thread comes back to job executing assembly its not supposed to.
Is that very likely?
What are the advantages of normal mutex lock defined in boost::thread? How it ensures that assembly CAN’T be split? Does it work as fast as boolean “mutex” like in example above?
Yes. I am being slightly glib, as likeliness depends on your program, the environment it is run in, etc. But if you want your code to be correct you should use a mutex.
You have identified the principle advantage: it is atomic and threadsafe. Thus making your code correct. If you want your program to output results deterministically (IE to be reliable) you have to use some type of threadsafe idiom.
Implementation is generally platform and hardware specific. One way to implement a mutex is to use a special assembly instruction “Compare And Swap”
There is very likely to be a cost for synchronization. To get great performance out of multithreaded programs synchronize state only when strictly necessary, as a last resort look in to lock free data structures. Here is a useful guide.