This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Optimization of conditional access to globals: thread-unsafe?
On 10/21/07, Tomash Brechko <tomash.brechko@gmail.com> wrote:
> On Sun, Oct 21, 2007 at 17:26:02 +0200, Erik Trulsson wrote:
> > Note that C99 is firmly based on a single-threaded execution model and says
> > nothing whatsoever about what should happen or not happen in a threaded
> > environment. According to C99 a C compiler is allowed to generate such code
> > as gcc does.
>
> Yes, I understand that C99 doesn't concern threads per see, but I
> wouldn't call it pro-single-threaded, rather thread-neutral. I.e. the
> standard isn't made explicitly incompatible with threads, it is
> simply "says nothing about threads".
>
>
> > If you are using some threaded environment then you will have to read the
> > relevant standard for that to find out if it imposes any additional
> > restricitions on a C compiler beyond what the C standard does.
>
> All we have is POSIX, and it imposes very little on compiler I guess.
>
>
> > I suspect that most of them will not say one way or the other about what
> > should happen in this case, which means that you will have to assume the
> > worst case and protect all calls to f() regardless of the value of the
> > argument.
>
> Well, assuming the worst case won't always work, that's why I asked
> about reasonable boundary. Consider the following (putting
> style/efficiency matters aside):
>
> #include <pthread.h>
>
> #define N 100
>
> /* mutex[i] corresponds to byte[i]. */
> pthread_mutex_t mutex[N];
> char byte[N];
>
> void
> f(int i)
> {
> pthread_mutex_lock(&mutex[i]);
> byte[i] = 1;
> pthread_mutex_unlock(&mutex[i]);
> }
>
>
> Is this code thread-safe? Because from some POV C99 doesn't forbid to
> load and store the whole word when single byte[i] is accessed (given
> that C99 is pro-single-threaded).
>
> But if C99 is thread-neutral, then it's compiler's responsibility to
> ensure the same result as some abstract machine (which may be
> sequential). In this case the compiler should access the single byte,
> no more.
On some architectures this is not even possible. For performance
reasons you should store the individual bytes to separate cache-lines
anyway.
Richard.