I was thinking about this when using mutex.
If you lock the thread with mutex for instance
m.lock();
a += b;
m.unlock();
What happens when the the two threads collide?
Is it like:
1) by locking thread A tells CPU that this must be executed uninterrupted until unlock
and while the a += b statement is happening context switch never occurs.
2) thread A locks, while doing the a += b statement context switch happens, thread B sees that its locked, yelds control and everything is back to A which finishes a += b; operation and unlocks access?
If it’s case 2 after all, is there a way to tell CPU that certain parts of the code shall never be interrupted by context switch?
It is 2, and there is no direct way to say that code must run to completion without a context switch. You could probably get close by bumping the execution priority of the thread but such shenanigans are usually frowned upon and suggest a bad design.