Subj : Re: 'volatile' Rules To : comp.programming.threads From : Marcin 'Qrczak' Kowalczyk Date : Wed Jun 08 2005 08:52 am Joe Seigh writes: > Until the signal handler exits, the main program doesn't see or do anything. > After the signal handler exits, the main program sees everything the signal > handler saw. Only if the compiler actually emits code to read the variable from memory. The default optimization assumption is that there are no asynchronous changes to variable, and that actual changes may be delayed to a convenient point. When several variables are modified by a signal handler, volatile ensures that the main program will read them in the correct order, as written in the source. For example if a signal handler does: if (x != 0) { y = x; x = 0; } and the main program does: z = x == 0 ? y : x; then volatile ensures that the code in the main program will not be compiled as if it was written: z = y; if (x != 0) z = x; which would be incorrect, as this might read y before a signal handler sets it yet test x after the signal handler, and use a bogus value of y. In theory this applies only to variables of type volatile sig_atomic_t, for other types read and write need not to be atomic. Extending it to volatile ints and volatile pointers is non-portable but I haven't heard of a system where it doesn't work, and it's sometimes very convenient. Using it with non-volatile variables is risky even with common compilers on common architectures. > I never depend on volatile for communicating with signal handlers. > I use other mechanisms for correct memory visibility. volatile is the mechanism for ensuring synchronization between the source and the CPU view of the program state. PThread functions which synchronize memory *also* synchronize between CPU views of different CPUs. They may not be used in signal handlers though. -- __("< Marcin Kowalczyk \__/ qrczak@knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ .