I've got an interrupt that sets a flag, a bool called recvd as so:
while (radio.available())
{
// Fetch the payload, and see if this was the last one.
radio.read( &receive_payload, len );
recvd = 1;
radio.writeAckPayload(1,&ack,sizeof(ack));
}
In my main() I've got a while(1) loop and a simple if statement checking if the flag has been set to 1:
// forever loop
while(1){
if (recvd == 1){toFloat(12);recvd = 0;}
}
}
This function is never called, even though I can put a printf inside the interrupt handler giving the value for recvd and it spits out 1. Any Ideas? Interestingly enough, when I put a random character printf just in the root of the while statement the if clause is called.
This is quite a good example of multithreading programming caveats. Actually, there are two of them:
Compiler-level optimization. If your compiler can make a suggestion about values and execution path, it can optimize your code. Sometimes, it does it very significantly (as Shafik Yaghmaour mentioned in comments above).
CPU-level optimization. Modern processors can execute your code very different way compared with what your compiler created. Most famous thing here is "out-of-order execution" which helps CPU to maximize code speed and increase memory/conveyor/etc throughputs. So, if your CPU decides there is no correlation between that two statements, it is no difference if they're executed in original order or in inversed order. Thus, one thread can run very ahead of another (and destroy your code logic). To avoid that, you have to learn about memory fences and other synchronization primitives, how they can affect your code.