Mutual exclusion using shared memory only is large area of study. I haven't seen simple examples of it that aren't tied to an OS. If you want to write your own, Wikipedia has a nice summary here:
http://en.wikipedia.org/wiki/Mutual_exclusion
I think there is no generic code out there because of the need to control instruction reordering in the processor or optimization in the compiler.