This is the mail archive of the
mailing list for the GCC project.
Re: Optimization of conditional access to globals: thread-unsafe?
On Mon, Oct 22, 2007 at 00:07:50 +0100, Dave Korn wrote:
> Because of the 'as-if' rule. Since the standard is neutral with regard to
> threads, gcc does not have to take them into account when it decides whether
> an optimisation would satisfy the 'as-if' rule.
If this would be true, then the compiler is free to inject the
mov mem -> reg
mov reg -> mem
just _anywhere_. How the programmer can predict where and when to
lock the mutex to protect mem? The only thing we could relay on then
is that the compiler is sound, it wouldn't inject such a sequence
unless it really feels so. But still, how to determine when the
compiler really feels so?
Here's another piece of code, more real and sound this time:
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int acquires_count = 0;
res = pthread_mutex_trylock(&mutex);
if (res == 0)
Is it thread safe? Or rather, should the compiler preserve its
thread-safeness, as seen from the programmer's POV? Otherwise I don't
get how pthread_mutex_trylock() could possibly ever be used, because
it's exactly the case when you _have_ to do the access based on the
condition, "assume the worst" won't work here. GCC 4.3 with -O1
movl %esp, %ebp
subl $8, %esp
movl $mutex, (%esp)
cmpl $1, %eax ; test res
movl acquires_count, %edx ; load
adcl $0, %edx ; maybe add 1
movl %edx, acquires_count ; store