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 22 October 2007 11:51, Tomash Brechko wrote:
> Can't agree less! That's why for _practical_ reasons I'd say GCC
> should be thread-aware, even if _theoretically_ it doesn't have to.
> And AFAIU it already _is_, for the most part of it. That's why I want
> to see Bug#31862 be confirmed, accepted, and fixed.
Re that particular bug, there are grounds to say that if gcc is going to
implement a flag -fopenmp, it should try and generate threading-compatible
code, I agree, but your point:
"And the essence of this bug report is that gcc chooses to unconditionally
write to variables that are simply lexically mentioned but otherwise aren't
accessed during execution."
is simply something that you have no right to expect of the compiler in the C
language unless you use volatile. Here's Jakub's original example:
"int var;
void
foo (int x)
{
int i;
for (i = 0; i < 100; i++)
{
if (i > x)
var = i;
}
}
When some other thread modifies var at the same time while foo (200) is
executed, the compiler inserted a race which doesn't really exist in the
original program, as it will do reg = var; ... var = reg; even when var was
never modified."
If var is volatile, the compiler won't do that, and it is I'm afraid the
right answer to the problem in this case: 'var' is inappropriately declared if
it is to be used from multiple threads in this way. And even volatile
wouldn't help if the code said
if (i > x)
var += i;
instead of a simple assignment. The race in fact *does* exist in the original
program, but is hidden by the fact that you don't care which of two operations
that overwrite the previous value complete in which order, but you're assuming
the operation that modifies var is atomic, and there's nothing to innately
guarantee that in the original program. The race condition *is* already
there.
There should really be a lock/unlock mutex sequence around the assignment to
var, but within the scope of the if condition. And at that point you'd find
that gcc didn't hoist anything past the subroutine calls to the mutex
lock/unlock and so only the code path through the then-part of the if would
ever touch the variable at all.
cheers,
DaveK
--
Can't think of a witty .sigline today....