[英]C++ std::thread combined with C pthread_mutex_t
Just a quick question on which I didn't find clear answer: 只是一个简短的问题,我没有找到明确的答案:
Is it completely safe to create C++ std::thread
s, in which I use pthread_mutex_t
for locking critical sections? 创建C ++
std::thread
完全安全吗,在其中我使用pthread_mutex_t
锁定关键部分吗?
EDIT : Mutexes locks parts of code to be safe from race conditioning. 编辑 :互斥锁可锁定部分代码,以免受到竞争条件的影响。 So I think it should have nothing to do with the matter of choosing C or C++ threads.
因此,我认为这与选择C或C ++线程无关。
Don't do it, that's what std::mutex 's are for, and if you want to further investigate you can google about all std::thread
related things. 不要这样做,这就是std :: mutex的用途,如果您想进一步调查,可以在Google上搜索所有与
std::thread
相关的东西。
I consider it important to point out, that I have never used std::thread
s in my life, but it's just a reasonable assumption that if there exists, std::thread
, there must be a std::mutex
, I typed std::mutex
in google and the page in the link I posted in this answer appeared. 我认为有必要指出,我一生中从未使用过
std::thread
,但这只是一个合理的假设,即如果存在std::thread
,则必须存在std::mutex
,我键入了std::mutex
了Google的std::mutex
和我在此答案中发布的链接中的页面。
For portability, use std::thread
and its associated structures like std::mutex
. 为了实现可移植性,请使用
std::thread
及其关联的结构,例如std::mutex
。 Minimize use of eg native handles etc. Using the std::
mechanisms also makes your code less buggy, by using RAII. 尽量减少对本机句柄等的使用。通过使用
std::
机制,还可以通过使用RAII来减少代码的错误。 Without it, even experienced programmers forget to unlock locks at eg exceptions. 没有它,即使经验丰富的程序员也忘记了在发生异常时解锁锁。
But here is a question similar to yours: Is it safe to mix pthread.h and C++11 standard library threading features? 但是这里有一个与您类似的问题: 将pthread.h和C ++ 11标准库线程功能混合使用是否安全?
use std::mutex, 使用std :: mutex,
or, you can use std::atomic with std::thread 或者,您可以将std :: atomic与std :: thread一起使用
// std::atomic<UINT8> a;
thread t(f, std::ref(a));
t.detach();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.