Curious global variable bug? Bad assumptions on my part?
Tom St Denis
tstdenis@ellipticsemi.com
Thu Feb 14 16:37:00 GMT 2008
Tynan Wilke wrote:
> Hello list,
>
> If I am posting in the wrong place, I apologize. I was making some
> test scripts this morning and found a pretty glaring difference
> between my optimized (-O1) versus my unoptimized (-O0) test code.
> Below, is the a quick example that I made showing the problem:
> --------------------------------
> #include <pthread.h>
> #include <stdio.h>
> #include <stdlib.h>
>
> static int g_counter = 0;
>
> void *IncThread(void* nothing)
> {
> printf("Thread started\n");
> while( 1 )
> {
> g_counter++;
> // printf("thread g_counter: %d\n", g_counter );
> }
> return NULL;
> }
>
> int main()
> {
> pthread_t thread;
> if ( 0 != pthread_create(&thread, NULL, IncThread, NULL ) )
> {
> perror("Failed to create thread");
> exit(1);
> }
>
> printf("Waiting for counter...\n");
> while ( g_counter == 0 );
>
Make g_counter volatile. And for the real spiffy, you should actually
have a lock around it's access. Congrats, you invented a race condition.
Basically what's happening is that g_counter is likely cached in a
register, and never read from memory after the initial expression.
Making it volatile will fix the bug on most platforms (where read/write
of an int is atomic). But the "correct" solution is to place a mutex
around it's access.
Tom
More information about the Gcc-help
mailing list