Compiler optimization messing synchronization

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

Post Reply
ianmga
Posts: 42
Joined: Fri Jan 28, 2011 1:11 am

Compiler optimization messing synchronization

Post 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
zyp
Posts: 6
Joined: Fri Apr 01, 2011 8:47 pm

Re: Compiler optimization messing synchronization

Post by zyp »

Use the volatile-keyword on the buffer to tell the compiler that writing the buffer has background effects.
User avatar
Giovanni
Site Admin
Posts: 14891
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 996 times

Re: Compiler optimization messing synchronization

Post 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
Post Reply