In other words we can say that lack of synchronization between the threads while using the shared resource ‘counter’ caused the problems or in one word we can say that this problem happened due to ‘Synchronization problem’ between two threads. The actual problem was the usage of the variable ‘counter’ by second thread when the first thread was using or about to use it. So we see that its not the repetitive log but the wrong value of the ‘counter’ variable that is the problem.So, when Job 1 actually got finished, then the wrong value of counter produced the log ‘Job 2 finished’ followed by the ‘Job 2 finished’ for the actual job 2 or vice versa as it is dependent on scheduler.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. 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.