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>
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);
}
BTW I'm running Debian Wheezy.
In which case, std::thread is sort of a wrapper for pthread. What should I use in C++: pthread or thread? On platforms where std::thread is adequately implemented (Linux, Win32) you should use it, unless you want to tweak with scheduling policies for threads or use pthread's non-portable extensions.
C++11 thread is an element of the C++ standard and provide a set of functionality that is comparable to the pthread library. If one compiles a C++ program using C++11 threads on unix then the resulting binary will be linked to the pthread library. On Windows system it will be linked to the windows thread library.
The pthread library is a unix C library that provides Posix Thread functionality. On windows system it is not available and instead there are the Windows Threads and a corresponding library (I can’t provide details, sorry). On other systems providing threading functionality there will be another one.
Let’s start with just threads, and the level at which you are hitting some confusion. When a thread is created, it’s created with certain thread attributes. These may be specified prior to calling pthread_create, or they may be defaulted. One of these is whether or not you can call pthread_join on the thread at some later point in
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With