Deadlocks happen when there are multiple process or threads waiting for each other to relinquish the control of the needed resources. It often appears as a circular list.
Deadlocks
-
The Pragmatic Programmer
Allocate a set of resources in the same order if such pattern should occur in different places such as in multithreading environment# . It is a precaution to avoid possible Deadlocks#.
-
Semaphore in System V
The flag for
semop()
are 0,IPC_NOWAIT
, andSEM_UNDO
. For flag value of 0,semop()
will simply suspend the process execution and keep it wait in queue for the semaphore set if the operation is not successful until it can perform it successfully.IPC_NOWAIT
changes that, so it will return immediately if the operation fails.SEM_UNDO
tellssemop()
to undo all operations done on the semaphore upon process exit which could be useful to prevent Deadlocks#. -
Mutex in Pthread
When the thread need to lock the mutex for multiple times, it is wise to use the recursive lock in order to prevent 202202191853. Since the default initialisation of mutex does not allow us to recursively lock it, we need to modify its attribute. To do that, we need to declare a
pthread_mutexattr_t
and then initialise it by callingpthread_mutexattr_init
. Set the correct type by callingpthread_mutexattr_settype
. When calling onpthread_mutex_init
, pass it to its second parameter. Later on, clean it up usingpthread_mutexattr_destroy
.