Lets see a piece of code where mutexes are used for thread synchronization #include
The first function above releases the lock and the second function destroys the lock so that it cannot be used anywhere in future. Int pthread_mutex_destroy(pthread_mutex_t *mutex) The mutex can be unlocked and destroyed by calling following functions : int pthread_mutex_unlock(pthread_mutex_t *mutex) The first function initializes a mutex and through second function any critical region in the code can be locked. Int pthread_mutex_lock(pthread_mutex_t *mutex) Hence, this system ensures synchronization among the threads while working on shared resources.Ī mutex is initialized and then a lock is achieved by calling the following two functions : int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr).So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.Mutex lock will only be released by the thread who locked it.
If the above assumption was true then the value of the ‘counter’ variable got incremented again before job 1 got finished.
The log ‘Job 2 started’ is printed just after ‘Job 1 Started’ so it can easily be concluded that while thread 1 was processing the scheduler scheduled the thread 2.But if you’ll have a closer look and visualize the execution of the code, you’ll find that : Now, if you go back at the code and try to find any logical flaw, you’ll probably not find any flaw easily. If you focus on the last two logs, you will see that the log ‘Job 2 finished’ is repeated twice while no log for ‘Job 1 finished’ is seen. The code and the flow looks fine but when we see the output : $. The above code is a simple one in which two threads(jobs) are created and in the start function of these threads, a counter is maintained through which user gets the logs about job number which is started and when it is completed. Printf("\ncan't create thread :", strerror(err)) Lets take an example code to study synchronization problems : #includeĮrr = pthread_create(&(tid), NULL, &doSomeThing, NULL) Linux Threads Series: part 1, part 2, part 3, part 4 (this article). In this article we will throw some light on an important aspect known as thread synchronization. To review, open the file in an editor that reveals hidden Unicode characters.In the Linux threads series, we discussed on the ways in which a thread can terminate and how the return status is passed on from the terminating thread to its parent thread. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below.