In the following code:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ready = 0;
wait()
{
int i;
do
{
usleep(1000);
pthead_mutex_lock(&mutex);
i = ready;
pthread_mutex_unlock(&mutex);
} while (i == 0);
printf("Finished
");
}
signal()
{
pthead_mutex_lock(&mutex);
ready = 1;
pthread_mutex_unlock(&mutex);
}
We spawn two threads we call wait in one thread and then call signal in the other We also get the compiler to optimize aggressively.
Now will the code behave as expected or will we need to make ready volatile to get this to work? Will different compilers and libraries handle this differently?
Edit: I am hoping that there might be something round the mutex functions that will prevent optimization around itself or that the compiler generally does not optimize round function calls.
Note: I have not compiled and tested the code yet, will do so when I have a chance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…