Is it okay to use std::this_thread* functions from

2019-04-24 21:27发布

问题:

Is it okay to mix and match things from boost::thread and std::thread, or should one set of functions be used for each?

I ask because my code uses boost::threads, but I've found that boost::this_thread::sleep_for doesn't behave properly when setting the system time back, but std::this_thread::sleep_for does, so I'd like to change my sleep function call and avoid changing all my boost::threads to std::threads if possible.

回答1:

In practice you might get away with things iff/because the implementations use the same implementations (e.g. pthread on linux).

However, you will be breaking invariants. Simple example: Boost Thread's interruption points won't function with non-boost synchronisation primitives (including std::this_thread::sleep_*).

Therefore I'd avice against actually mixing libraries for controlling related threads, lest you want to risk running into suprises ¹

Of course, if libraries have completely separate concerns (e.g. they use threads internally, "in the black box"), there should be no issue combining those libraries in one process.


¹ I can see deadlocks happening, and data races/leaks do not require a huge stretch of imagination (think thread local data support/call_once/set_value_at_thread_exit...)



回答2:

It is inadvisable to mix APIs within one thread. As @Jerry Coffin mentions, you may well run into undefined behaviour. There may be thread local state that these APIs rely upon that would not be compatible with threads created by a different API.

However, it should be fine to use std::thread and boost::thread separately within the one process. Since @Red Alert says 1.58 fixes the bug, this should solve your problem. Otherwise, you can temporarily revert to usleep() and similar functions with #ifdefs for different platforms.