结论:
最终std::mutex 会调用pthread_mutex_t 相关接口
1 std::mutex 定义封装关键数据:typedef __gthread_mutex_t
#ifdef _GLIBCXX_HAS_GTHREADS
// Common base class for std::mutex and std::timed_mutex
class __mutex_base
{
protected:
typedef __gthread_mutex_t __native_type;
#ifdef __GTHREAD_MUTEX_INIT
__native_type _M_mutex = __GTHREAD_MUTEX_INIT;
constexpr __mutex_base() noexcept = default;
#else
__native_type _M_mutex;
__mutex_base() noexcept
{
// XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
__GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
}
~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); }
#endif
__mutex_base(const __mutex_base&) = delete;
__mutex_base& operator=(const __mutex_base&) = delete;
};
/// The standard mutex type.
class mutex : private __mutex_base
{
public:
typedef __native_type* native_handle_type;
#ifdef __GTHREAD_MUTEX_INIT
constexpr
#endif
mutex() noexcept = default;
~mutex() = default;
mutex(const mutex&) = delete;
mutex& operator=(const mutex&) = delete;
void
lock()
{
int __e = __gthread_mutex_lock(&_M_mutex);
// EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
if (__e)
__throw_system_error(__e);
}
bool
try_lock() noexcept
{
// XXX EINVAL, EAGAIN, EBUSY
return !__gthread_mutex_trylock(&_M_mutex);
}
void
unlock()
{
// XXX EINVAL, EAGAIN, EPERM
__gthread_mutex_unlock(&_M_mutex);
}
native_handle_type
native_handle() noexcept
{ return &_M_mutex; }
};
#endif // _GLIBCXX_HAS_GTHREADS
typedef pthread_t __gthread_t;
typedef pthread_key_t __gthread_key_t;
typedef pthread_once_t __gthread_once_t;
typedef pthread_mutex_t __gthread_mutex_t;
typedef pthread_mutex_t __gthread_recursive_mutex_t;
typedef pthread_cond_t __gthread_cond_t;
typedef struct timespec __gthread_time_t;
typedef union
{
struct __pthread_mutex_s __data;
char __size[__SIZEOF_PTHREAD_MUTEX_T];
long int __align;
} pthread_mutex_t;
struct __pthread_mutex_s
{
int __lock;
unsigned int __count;
int __owner;
#ifdef __x86_64__
unsigned int __nusers;
#endif
/* KIND must stay at this position in the structure to maintain
binary compatibility with static initializers. */
int __kind;
#ifdef __x86_64__
short __spins;
short __elision;
__pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV 1
#else
unsigned int __nusers;
__extension__ union
{
struct
{
short __espins;
short __eelision;
# define __spins __elision_data.__espins
# define __elision __elision_data.__eelision
} __elision_data;
__pthread_slist_t __list;
};
# define __PTHREAD_MUTEX_HAVE_PREV 0
#endif
};
# define __SIZEOF_PTHREAD_MUTEX_T 40
编译时候必须指定链接库:-lpthread
caros@caros-Alienware-m15-R6:~/study/C++_std/thread$ g++ mutex.cpp
/usr/bin/ld: /tmp/ccZoZxMe.o: in function `std::thread::thread<void (&)(int), int, void>(void (&)(int), int&&)':
mutex.cpp:(.text._ZNSt6threadC2IRFviEJiEvEEOT_DpOT0_[_ZNSt6threadC5IRFviEJiEvEEOT_DpOT0_]+0x37): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
caros@caros-Alienware-m15-R6:~/study/C++_std/thread$ g++ mutex.cpp -lpthread
参考文档: