Page 1 of 1

Compiler optimization messing synchronization

Posted: Sun Apr 03, 2011 9:29 pm
by ianmga
Hi,

While stepping through the code debugging something else I realized with shock that the compiler had rearranged the instructions in an order that would mess up the thread synchronization big time (changed writing to buffer and signaling a semaphore into the ...opposite ordering). I went searching and turns out this is not an unusual complaint working with multithreaded apps.

Is the ChibiOS code somewhat safe from this?? What can I do to avoid this happening when compiling the RTOS? (other than turning off optimization, but it may have to come to that)

Ian

Re: Compiler optimization messing synchronization

Posted: Mon Apr 04, 2011 8:56 pm
by zyp
Use the volatile-keyword on the buffer to tell the compiler that writing the buffer has background effects.

Re: Compiler optimization messing synchronization

Posted: Tue Apr 05, 2011 6:44 am
by Giovanni
I totally missed this thread... sorry.

Yes, declaring the buffer volatile should work but I think the compiler should not move stuff across a function call because the function could modify the buffer itself (is the buffer global or local to the function? if it is local try to make it global, this would prevent optimizations and assumptions).

Giovanni