proper linking of boost multithreaded libraries on

2019-09-14 23:49发布

问题:

I'm a bit confused about whether to link against the libboot_*-mt variants or not and what they're actually used for.

I'm using a custom backport of boost 1.46.0 on Centos 6. The build produces /usr/lib64/libboost_thread-mt.so.7 as well as -mt and standard versions of the other libraries.

I've written a unit test program which uses a thread to store a calculation in a boost::future. To link that test I had to add -lboost_thread-mt. But I did not need to change the other boost -l args to use the -mt versions.

I've read the Library Naming section on the boost site but it's not clear to me what "indicates that the library was built with multithreading support enabled. Libraries built without multithreading support can be identified by the absence of -mt" actually means.

  1. Do i need to switch to the multithreading-aware versions of the other libraries if I link with -lboost_thread-mt? If not, when do I need to link against the -mt variants?

  2. Is there a recommendation for selectively linking against the -mt variants only if they're needed? This project uses GNU Make for builds.

  3. Is there a performance or functional penalty for always linking against the -mt variants?

回答1:

The "mt" variant is built when you set threading=multi in bjam line. One of the consequences of "mt" option is that BOOST_HAS_THREADS is defined.

Of course, all the boost libs you link shound be of the same variant, which matches the threading of your application. Otherwise you can end up with ODR violation: imagine that one compiles shared_ptr in library A without BOOST_HAS_THREADS, while library B - with BOOST_HAS_THREADS. The two shared_ptr's have completely different implementation of spinlock class. So, if you get shared_ptr from lib A and pass it to lib B, your program crashes. Besides, mt and non-mt variants might use different heaps.

(That's said, it's worth mentioning that BOOST_HAS_THREADS depends on some other macros, and can be defined even in a non-mt variant, so mixing mt with non-mt can occasionally work -- but don't rely on this.)

As for performance penalty - obviously, the mt variant may be a bit slower.

UPDATE: My assumption regarding BOOST_HAS_THREADS appears to be wrong. Still, it's a bad idea to mix mt/non-mt variants, as threading=multi affects Boost ABI.