I’m learning thread synchronization and this is the demo to show how to lock critical data when a thread is executing:
http://ideone.com/7Do0l
(To run this code, compile it with the -pthread parameter in Linux/MacOS environment)
The program works as expected, but the sleep() function doesn’t pause the execution between threads. My idea is to have one thread do the calculation at a time, then 1 second later another thread comes into play. Here is the code segment I’m fighting with:
while(1) {
//sleep(1); //(1) (Sleep for one second)
sem_wait(&mutex);
//sleep(1); //(2)
printf("Thread #%d is doing math. %d + 1 = %d.\n", (int) id, s, s+1);
s++;
//sleep(1); //(3)
sem_post(&mutex);
//sleep(1); //(4)
}
There are four positions I have tried to put the sleep() in. (1) and (4) result in no pauses between single threads but between two bunches of ten threads. (2) and (3) result in one thread gets executed repeatedly for very long time before another gets called.
Is there a remedy to this?
Update
There is a trick to make the program produce the result: generating the sleeping time randomly for each thread, but it’s not consistent since two random numbers could be the same by accident.
I did some research and found that the only way to produce the desired output is the one I mentioned in the Update part. That is, instead of hard coded the sleep timer, just give each thread a random number:
And actually I have been over-worrying about two threads doing the same thing at once. Even though the two adjacent random timers could be accidentally the same, two threads never get executed on the same core of the CPU at the same time, in case the CPU is of multiple cores, no two instructions can modify the same memory content concurrently.