简体   繁体   English

何时使用pthread_mutex_t

[英]When to use pthread_mutex_t

Can someone please explain in what scenario's it would be beneficial to use std::mutex vs pthread_mutex_t. 有人可以解释在什么情况下使用std :: mutex vs pthread_mutex_t是有益的。 I dont understand why we would ever use pthread_mutex_t. 我不明白为什么我们会使用pthread_mutex_t。 Thanks 谢谢

The pthread_mutex_t is a POSIX solution (available for linux and other UNIX systems) that existed before c++11 introduced synchronisation primitives into the c++ library. pthread_mutex_t是一个POSIX解决方案(可用于Linux和其他UNIX系统),它在c ++ 11将同步原语引入c ++库之前就已存在。 You should use std::mutex now, amongst other things it is more cross-platform (can be used under Windows also). 您现在应该使用std::mutex ,其中包括更多跨平台(也可以在Windows下使用)。

std::mutex is just a thin wrapper around pthread_mutex on systems supporting pthreads. std :: mutex只是支持pthreads的系统上pthread_mutex的一个瘦包装器。

In general, the operations on the std:: thread primitives are quite limited vs the native versions (pthreads or windows threads). 通常,对std :: thread原语的操作与本机版本(pthreads或windows threads)相比非常有限。 If you don't need those features, you should always use the std:: versions, but if you do need the advanced features, then you have no choice but to use the native version. 如果您不需要这些功能,则应始终使用std ::版本,但如果确实需要高级功能,则除了使用本机版本之外别无选择。

native handle() method exists for exactly this reason. native handle()方法正是出于这个原因。

std::mutex is from standard library, so if you use it your code will compile also on platforms where pthreads are not provided. std::mutex来自标准库,因此如果您使用它,您的代码也将在未提供pthread的平台上编译。 For example under windows std::mutex uses native WinAPI mutex implementation. 例如,在windows下, std::mutex使用本机WinAPI互斥实现。

Its best to always use std::mutex . 最好总是使用std::mutex

See pthread_mutexattr for an idea of the other flavors of POSIX mutexes available besides the default. 有关默认情况下可用的其他POSIX互斥体的概念,请参阅pthread_mutexattr。 Though one of the main ones-- recursive vs. nonrecursive-- is available with std::recursive_mutex, this is not true for things like BSD priority ceilings, etc. 虽然std :: recursive_mutex可以使用其中一个主要的 - 递归与非递归 - 但对于BSD优先级上限等问题却不是这样。

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

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