Segmentation fault when accessing statically initialized __thread variable

1.2k views Asked by At

Consider the following code:

#include <stdio.h>

__thread bool foo = true;

int
main() {
    printf("foo = %d\n", foo);
    return 0;
}

Compile and run with:

$ g++ tls.cpp -o tls -o tls
$ ./tls

On some systems -- such as Amazon Linux 2013.09.0, ami-5b792c32, kernel 3.4.62-53.42.amzn1.i686, g++ 4.6.3 20120306 (Red Hat 4.6.3-2) -- this results in a segmentation fault as soon as foo is accessed.

On the other hand, explicitly initializing foo in code does not result in a segmentation fault:

#include <stdio.h>

__thread bool foo = true;

int
main() {
    foo = true;  /* Added!! */
    printf("foo = %d\n", foo);
    return 0;
}

Why does the first code example crash on some system, while the latter does not? Is static initialization of __thread variables not supposed to work? May the operating system be broken?

1

There are 1 answers

3
David Schwartz On

You forgot to tell the compiler you want threads support. Most likely, the flag is -pthread.