4

We know that adding -pthread makes GCC use reentrant/thread-safe code (when compiling C/C++ code). While I guess it's true you might save a couple of cycles here and there if you allow non-reentrancy - I wonder whether there's any actual advantage to not always specifying -pthread. Is there?

Community
  • 1
  • 1
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • The generated code is not reentrant anyway? I did not know that gcc was so monstrously unsafe to use. – Martin James Mar 18 '16 at 09:34
  • ..or do you only mean libraries? That I could understand:) – Martin James Mar 18 '16 at 10:09
  • @MartinJames: I meant it in the sense described in the link. `#define REENTRANT` depends on `-lpthread`. I'm not sure exactly what changes; but the answers here already present one not-insignificant example. – einpoklum Mar 18 '16 at 12:40

2 Answers2

4

One example: the libstdc++ implementation of std::shared_ptr doesn't use locking when compiled without -pthread, which can give you a nice boost to performance if you're using shared pointers heavily in a single-threaded environment.

Community
  • 1
  • 1
Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
0

In c++ the philosophy of the language has always been "you don't pay for what you don't need". If your program runs single threaded and do not need reentrant functions there's no real incentive to add -pthread.

The cost of using a reentrant function is always going to be higher or equal to the non-reentrant version of a function. Either in time (you have to lock mutexes to protect variables), or allocate memory per function invocation instead of using a static buffer.

In addition, some platforms may not have a pthreads implementation ( pthreads is a POSIX thing after all).

Louen
  • 3,617
  • 1
  • 29
  • 49
  • 2
    I don't see how it answers the question. – YSC Mar 18 '16 at 09:10
  • @YSC: Actually I think that's a valid point. It would be "methodically inconsistent" to force reentrancy on you. This consistency is a sort of a benefit. – einpoklum Mar 18 '16 at 09:50
  • @YSC : It is true I could have made it clearer that there's always going to be a performance cost to use the reentrant version of some functions (off the top of my head, strok and strok_r for example, so if you don't need pthreads (and performance is an issue) you might not want to use it. – Louen Mar 18 '16 at 09:57
  • 1
    OP already knows that. Specifics are expected of a good answer. – YSC Mar 18 '16 at 09:59
  • Hmmm...Para (1) and (3) are irrelevant to the question. Para (2) touches the topic but implies that -pthread enforces re-entrancy (and it affects performance) which requires some sort of evidence or at least a decent example, IMO. – P.P Mar 18 '16 at 10:18