This is the mail archive of the
mailing list for the GCC project.
RE: Optimization of conditional access to globals: thread-unsafe?
- From: "Dave Korn" <dave dot korn at artimi dot com>
- To: "'Tomash Brechko'" <tomash dot brechko at gmail dot com>, <gcc at gcc dot gnu dot org>
- Date: Mon, 22 Oct 2007 00:07:50 +0100
- Subject: RE: Optimization of conditional access to globals: thread-unsafe?
- References: <20071021145513.GB4925@moonlight.home>
On 21 October 2007 15:55, Tomash Brechko wrote:
> Consider this piece of code:
> extern int v;
> f(int set_v)
> if (set_v)
> v = 1;
> pushl %ebp
> movl %esp, %ebp
> cmpl $0, 8(%ebp)
> movl $1, %eax
> cmove v, %eax ; load (maybe)
> movl %eax, v ; store (always)
> popl %ebp
> Note the last unconditional store to v.
> So, could someone explain me why this GCC optimization is valid,
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 you really want all externally-visible accesses to v to be made exactly
as the code directs, rather than allowing gcc to optimise them in any way that
(from the program's POV) it's just the same 'as-if' they had been done
exactly, make v volatile.
Can't think of a witty .sigline today....