lundi 25 mai 2020

Deduce if a program is going to use threads

Thread-safe or thread-compatible code is good. However there are cases in which one could implement things differently (more simply or more efficiently) if one knows that the program will not be using threads.

For example, I once heard that things like std::shared_ptr could use different implementations to optimize the non-threaded case (but I can't find a reference). I think historically std::string in some implementation could use Copy-on-write in non-threaded code.

I am not in favor or against these techniques but I would like to know if that there is a way, (at least a nominal way) to determine at compile time if the code is being compiled with the intention of using threads.

The closest I could get is to realize that threaded code is usually (?) compiled with the -pthreads (not -lpthreads) compiler option. (Not sure if it is a hard requirement or just recommended.)

In turn -pthreads defines some macros, like _REENTRANT or _THREAD_SAFE, at least in gcc and clang. In some some answers in SO, I also read that they are obsolete.

Are these macros the right way to determine if the program is intended to be used with threads? (e.g. threads launched from that same program). Are there other mechanism to detect this at compile time? How confident would the detection method be?

Aucun commentaire:

Enregistrer un commentaire