Payoff Payoff - 17 days ago 5
C Question

Weird problems with variables and multiple threads

I have a program with multiple threads.
In my main thread I examine in a permanent loop whether a global variable has the value 1.
This variable I set during the runtime in the other thread with a Mutex locked on it to 1.
So the if condition should be true in the main thread. But it doesn't work... But if i put a printf before the if condition it works. This is so weird I have no idea whats wrong. Thanks

The code:

while(1)
{
printf("\n");
if(logging_active == 1) {
//check filesize every 30s. If logfile size over 1MB (1.000.000) send file
if((timestamp_realtime_sec() - last_time) >= ((logtime+1))) {
printf("check filesize...\n");
if(fileSize("log") > 100000) {
logfileHandler("log");
}
last_time = timestamp_realtime_sec();
}
}
}


Output:

check filesize ...


Without the printf it's output nothing.

Solution for me:
changing the variable declaration from
int logging_active
to
volatile int logging_active
solved the problem.

Answer

The compiler doesn't know you're updating the variable from another thread, so it may not be actually checking it every time. Mark the variable as volatile and it should work as you expect. This tells the compiler that it isn't allowed to omit loads from that variable--it really has to read it every time.