是否可以安全地混合pthread.h和C ++ 11标准库的线程特性? [英] Is it safe to mix pthread.h and C++11 standard library threading features?
问题描述
我可以用 pthread_create
产生一个线程,并安全地使用 std :: mutex
吗?
我认为如果 std :: mutex
被实现为 pthread_mutex_t $ c $
<$ p $ p>
#include< pthread.h>
#include< mutex>
std :: mutex global_lock;
void * thread_func(void * vp)
{
global_lock.lock(); // std :: mutex used in thread spawned with pthread_create
//关键部分
global_lock.unlock();
return NULL;
}
int main(void)
{
pthread_t tid;
pthread_create(& tid,NULL,& thread_func,NULL); $ b $ p pthread_join(tid,NULL);
return 0;
}
我运行Debian Wheezy。
你可以在我的机器上(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;
我不知道是否有一个文档化的方式来检查是否使用pthread。但 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 ++不使用pthread_t
Can I spawn a thread with pthread_create
and use std::mutex
inside of it safely?
I would think that if std::mutex
is implemented as a pthread_mutex_t
then it would be fine but I don't see this documented anywhere
For example:
#include <pthread.h>
#include <mutex>
std::mutex global_lock;
void *thread_func(void *vp)
{
global_lock.lock(); // std::mutex used in thread spawned with pthread_create
//critical section
global_lock.unlock();
return NULL;
}
int main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, &thread_func, NULL);
pthread_join(tid, NULL);
return 0;
}
BTW I'm running Debian Wheezy.
You could on my machine (Debian too). But I'm not sure if I would call this safe.
If you look at the relevant file, /usr/include/c++/4.7/i486-linux-gnu/bits/gthr-default.h
in my case, you will see that there will be a 1:1 mapping to the pthreads api. <mutex>
uses __gthread_mutex_lock
for locking which is defined exactly there to pthread_mutex_lock
. Or you will see that std::thread
declares typedef __gthread_t native_handle_type;
I don't know if there is a documented way to check if pthreads are used. But gthr-default.h
defines _GLIBCXX_GCC_GTHR_POSIX_H
as include guard and I think as long as this macro is defined, you can assume that you can mix them both.
Edit: Given the hint from @Wakely, I would write:
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");
这篇关于是否可以安全地混合pthread.h和C ++ 11标准库的线程特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!