This is the mail archive of the
mailing list for the GCC project.
Re: Optimization of conditional access to globals: thread-unsafe?
- From: "Bart Van Assche" <bart dot vanassche at gmail dot com>
- To: "Andrew Haley" <aph-gcc at littlepinkcloud dot com>
- Cc: gcc at gcc dot gnu dot org, "Andrew Pinski" <pinskia at gmail dot com>, "Tomash Brechko" <tomash dot brechko at gmail dot com>, "Florian Weimer" <fw at deneb dot enyo dot de>
- Date: Sat, 27 Oct 2007 14:10:28 +0200
- Subject: Re: Optimization of conditional access to globals: thread-unsafe?
- References: <email@example.com> <firstname.lastname@example.org> <email@example.com>
> > On 10/22/07, Andrew Haley <aph-gcc at littlepinkcloud dot COM> wrote:
> > > The core problem here seems to be that the "C with threads" memory
> > > model isn't sufficiently well-defined to make a determination
> > > possible. You're assuming that you have no responsibility to mark
> > > shared memory protected by a mutex as volatile, but I know of nothing
> > > in the C standard that makes such a guarantee. A prudent programmer
> > > will make conservative assumptions.
I'd like to return on this. Variables that are shared over two or more
threads can be classified as follows:
- static variables, global variables and dynamically allocated data.
- variables allocated on the stack.
As known the compiler may not reorder any access to any static
variable, global variable or dynamically allocated data with a call to
a function that is not declared inline. Variables that are allocated
on the stack of a thread can only be shared with another thread only
by passing a pointer to that variable to another thread first. Passing
such a pointer inhibits reordering of accesses to shared local
variables with a call to a function that is not declared inline.
Or: a C/C++ compiler will never reorder accesses to shared variables
with function calls. So if accesses to shared variables are properly
guarded with calls to synchronization functions, it is not necessary
to declare these shared variables volatile.
There is one category of synchronization functions that has not yet
been discussed: synchronization functions that can be inlined. I
propose to require that such synchronization functions contain at
least one asm statement that specifies that it clobbers memory,
because this inhibits reordering between the inlined synchronization
function and accesses to variables.
Maybe it's a good idea to add a chapter to the gcc manual about
multithreaded programming, such that gcc users who did not follow this
discussion can look up this kind of information easily ?
Bart Van Assche.