Rya*_*ing 21 c++ mutex pthreads c++11
我可以生成一个线程pthread_create
并std::mutex
安全地使用它吗?
我认为如果std::mutex
实现为a pthread_mutex_t
那么它会很好,但我没有看到任何记录
例如:
#include <pthread.h>
#include <mutex>
namespace {
std::mutex global_lock;
}
void* thread_func(void* vp) {
// std::mutex used in thread spawned with pthread_create
std::lock_guard<std::mutex> guard(global_lock);
// critical section
return nullptr;
}
int main() {
pthread_t tid;
pthread_create(&tid, nullptr, thread_func, nullptr);
pthread_join(tid, NULL);
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,我正在运行Debian Wheezy.
在任何规范中都没有保证它可以工作,但是在使用pthreads作为其唯一真正的线程库的操作系统上的任何C++实现都可能在C++线程下使用pthread,因此它可能会起作用.
如果您稍后尝试将代码移植到使用除pthread之外的其他平台,即使该平台也支持pthreads(例如,windows),您可能会遇到问题.
问题是,为什么要费心并冒风险呢?如果您使用的是C++ 11 std::mutex
,为什么不使用std::thread
?
你可以在我的机器上(Debian).但我不确定我是否会称之为安全.
如果您查看相关文件,/usr/include/c++/4.7/i486-linux-gnu/bits/gthr-default.h
在我的情况下,您将看到将有1:1映射到pthreads api.<mutex>
使用__gthread_mutex_lock
针对其精确定义那里锁定pthread_mutex_lock
.或者你会看到std::thread
声明typedef __gthread_t native_handle_type;
我不知道是否有记录的方法来检查是否使用了pthreads.但gthr-default.h
定义_GLIBCXX_GCC_GTHR_POSIX_H
为包含防护,我认为只要定义了这个宏,你可以假设你可以将它们混合起来.
编辑:鉴于@Wakely的提示,我会写:
template <typename T>
using strip = typename std::remove_pointer<typename std::decay<T>::type>::type;
static_assert(std::is_same<strip<std::thread::native_handle_type>, pthread_t>::value,
"libstdc++ doesn't use pthread_t");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5830 次 |
最近记录: |