Code before/after lock always execute serially?

152 Views Asked by At
CodeBlockA;

Lock;
CodeBlockB;
Unlock;

CodeBlockC

Code block may contain a lot of code, just take it as a unit.

Is CodeBlockA CodeBlockB CodeBlockC always execute in serial? How lock achieve this?

1

There are 1 best solutions below

2
Erdal Küçük On

Now, i don't know about other systems but on linux it is like this:

pthreads

In NPTL, thread synchronization primitives (mutexes, thread joining, and so on) are implemented using the Linux futex(2) system call.

futex

When executing a futex operation that requests to block a thread, the kernel will block only if the futex word has the value that the calling thread supplied (as one of the arguments of the futex() call) as the expected value of the futex word. The loading of the futex word's value, the comparison of that value with the expected value, and the actual blocking will happen atomically and will be totally ordered with respect to concurrent operations performed by other threads on the same futex word. Thus, the futex word is used to connect the synchronization in user space with the implementation of blocking by the kernel. Analogously to an atomic compare-and-exchange operation that potentially changes shared memory, blocking via a futex is an atomic compare-and-block operation.

C - mtx_lock

Prior calls to mtx_unlock on the same mutex synchronize-with this operation, and all lock/unlock operations on any given mutex form a single total order (similar to the modification order of an atomic)

C Standard n2596

7.26.4 Mutex functions

For purposes of determining the existence of a data race, lock and unlock operations behave as atomic operations. All lock and unlock operations on a particular mutex occur in some particular total order.

NOTE This total order can be viewed as the modification order of the mutex.