Question

I have a multi-threaded C/C++ program that services read and write requests very frequently. For synchronization purposes, I have used a mutex for locks and unlocks. All read and write threads acquire lock before performing their operations. What happens if one thread acquires lock and before it could release the locks, interrupt occurs ? Would the thread resume execution or I would have to handle it manually ?

Was it helpful?

Solution

User-side locks, including Mutexes do not block interrupts. This is important, since often a Mutex may be used to protect a read from a file on disk, or protect the reception of packets from a network, and such, where the result is reliant on an interrupt.

In essence, "nothing" happens if there is an interrupt. Interrupts are handled by the OS, just like any other time. There is nothing your program needs to do in this case, it just takes a few microseconds or milliseconds longer to do whatever you programmed your task to do if this happens.

Some kernel-side locks, such as SpinLocks do indeed block interrupts (on that processor core) to ensure that other processes/threads do not get scheduled during this process. There are also restrictions on what functions the kernel can use under these circumstances - for example, it wouldn't be possible to call a blocking function (such as a sleep, wait-for-event or file-read or file-write) during this time, because that would, potentially, cause the kernel to lock up.

OTHER TIPS

The thread will eventually resume execution, it may happen immediately following the kernel servicing the interrupt or the kernel scheduler may decide to dispatch another thread that is ready to run. If the interrupted thread has acquired a lock that is heavily contested, then other threads attempting to acquire that lock will block (or spin, or spin and then block, depending on the implementation of the mutex) until the interrupted thread is dispatched again, finishes the critical section protected by the lock, and unlocks it.

In systems that require near real time performance careful tuning is done to assign critical threads to their own cores (cpu affinity) and to map interrupts to other cores. Also, careful attention is paid to the use of locks, sometimes using algorithms that are lockless.

The fact that a thread has a lock is not influenced by signals. If a thread has a lock and receive a signal, nothing special will happen. In fact, signals and threads does not mix well as signals were designed with processes in mind. That is because you can not know which thread will get the signal. The right way to deal with that is to have a specific thread to manage signals, eg block all signals in every threads but one, which only duty is to handle signals. That the right way to deal with signals in a software which have threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top