views:

600

answers:

2

In various multi threaded C and C++ projects I've seen the -pthread flag applied to both the compiling and linking stage while others don't use it at all and just pass -lpthread to the linking stage.

Is there any danger not compiling and linking with the -pthread flag - i.e. what does -pthread actully do ? I'm primarly interrested in linux platforms.

+8  A: 

Try:

gcc -dumpspecs | grep pthread

On my computer, this causes files to be compiled with -D_REENTRANT, and linked with -lpthread. On other platforms, this will differ. Use -pthread for most portability.

Using _REENTRANT, on GNU libc, changes the way some libc headers work. As a specific example, it makes errno call a function returning a thread-local location.

Chris Jester-Young
It may not just be `errno` and preprocessing in general. I'm not sure how relevant the article http://www.hpl.hp.com/techreports/2004/HPL-2004-209.pdf is in practice for gcc optimizations, but I sure was impressed by the depth of the review there.
Pascal Cuoq
I don't think the errno example is correct. Even without a -pthread flag or _REENTRANT define, my errno.h (glibc 2.10.1) and gcc (4.4.1 on amd64) generates a dynamic call for errno handling and doesn't link against the symbol address.
Andy Ross
@Andy: I just did a grep for `_REENTRANT` in `/usr/include`; I'm sure there are other examples of its use.
Chris Jester-Young
@Pascal: Thanks for the link. It goes a bit above my head at the moment, but it seems that the central point is that threading cannot just be "tacked on", but instead must be designed in as part of the memory model. I completely agree with that.
Chris Jester-Young
@Andy - your version of gcc may be built to provide `-D_REENTRANT` or `-pthread` automatically. Run your build with `g++ -v` and it will dump a lot of output about what parameters the compiler front-end is actually passing to `cc1plus` and `ld`.
Tom
I know how it can be made to work. I was just quibbling with the example, which is not true on (at least) Ubuntu 9.10, as verified by examining the generated assembly. As far as I can tell, a typical glibc build treats -pthread as synonymous wiht -lpthread.
Andy Ross
+1  A: 

From man gcc:

-pthread Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.

Dmitry