简体   繁体   English

可以使用boost :: threads中的std :: this_thread *函数吗?

[英]Is it okay to use std::this_thread* functions from boost::threads?

Is it okay to mix and match things from boost::thread and std::thread , or should one set of functions be used for each? 可以混合和匹配boost::threadstd::thread ,还是应该为每个函数使用一组函数?

I ask because my code uses boost::thread s, 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::thread s to std::thread s if possible. 我问,因为我的代码使用了boost::thread ,但是我发现在设置系统时间时boost::this_thread::sleep_for行为不正常,但std::this_thread::sleep_for确实如此,所以我'我想改变我的睡眠函数调用,并尽可能避免将我的所有boost::thread s更改为std::thread

In practice you might get away with things iff/because the implementations use the same implementations (eg pthread on linux). 在实践中,你可能会忘记iff /因为实现使用相同的实现(例如linux上的pthread )。

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_* ). 简单示例:Boost Thread的中断点不能与非boost同步原语(包括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 (eg 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 ...) ¹我可以看到发生死锁,数据竞争/泄漏不需要大量的想象力(想想线程本地数据支持/ call_once / set_value_at_thread_exit ......)

It is inadvisable to mix APIs within one thread. 在一个线程内混合API是不可取的。 As @Jerry Coffin mentions, you may well run into undefined behaviour. 正如@Jerry Coffin所提到的,你可能会遇到未定义的行为。 There may be thread local state that these APIs rely upon that would not be compatible with threads created by a different API. 可能存在这些API所依赖的线程本地状态,这与不同API创建的线程不兼容。

However, it should be fine to use std::thread and boost::thread separately within the one process. 但是,在一个进程中单独使用std::threadboost::thread应该没问题。 Since @Red Alert says 1.58 fixes the bug, this should solve your problem. 由于@Red Alert说1.58修复了这个bug,这应该可以解决你的问题。 Otherwise, you can temporarily revert to usleep() and similar functions with #ifdef s for different platforms. 否则,您可以使用#ifdef s暂时恢复到usleep()和类似的功能,以用于不同的平台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM