Re: how to cast away 'volatile'?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Andrew Haley wrote:
Michael Eager writes:

 > It can also be used to share data between threads, but it becomes
 > problematic if accesses are not atomic.  It's reasonable to use a
 > shared volatile sig_atomic_t to communicate between threads, to say
> "I'm done" or "Start processing".
Is that really safe, though?  There's nothing to stop the machine from
reordering memory writes, even if the compiler doesn't.

Yes, it's safe.  It doesn't matter which microsecond that the flag is set.
(Or if it does, then your code should be using a mutex or some other
form of synchronization.)

Say you have one thread which performs some process when it sees
a shared flag set.  It checks this flag every second.  If another
process sets this flag, the service thread will notice and take action.

If the signaling process and the receiving process both try to
access the shared memory at the same time, the processor may
reorder the operations as it chooses.  The worst case is that
the server will check and see that the flag is not set, then
the signaling process will set the flag.  The result is a short
delay in the receiving process noticing that the flag is set.

Note that there is a race condition which is problematic.  If the
receiving process clears the flag, at the same time that the
signaling process sets it, then these may be reordered.  So you
need to insure that only one of the processes ever writes to the
flag.


--
Michael Eager	 eager@xxxxxxxxxxxx
1960 Park Blvd., Palo Alto, CA 94306  650-325-8077

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux