mutex在标准库里面的实现
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);
if (__e)
__throw_system_error(__e);
}
bool
try_lock() noexcept
{
return !__gthread_mutex_trylock(&_M_mutex);
}
void
unlock()
{
__gthread_mutex_unlock(&_M_mutex);
}
native_handle_type
native_handle()
{ return &_M_mutex; }
};
lock_guard在标准库里面的实现
template<typename _Mutex>
class lock_guard
{
public:
typedef _Mutex mutex_type;
explicit lock_guard(mutex_type& __m) : _M_device(__m)
{ _M_device.lock(); }
lock_guard(mutex_type& __m, adopt_lock_t) : _M_device(__m)
{ }
~lock_guard()
{ _M_device.unlock(); }
lock_guard(const lock_guard&) = delete;
lock_guard& operator=(const lock_guard&) = delete;
private:
mutex_type& _M_device;
};
使用记录
static int g_count = 100;
void fun_count1(std::mutex* mutex)
{
while(g_count > 0){
mutex->lock();
if(g_count > 0){
cout <<"fun_count1:"<<--g_count<<endl;
}
mutex->unlock();
usleep(1000*500);
}
}
void fun_count2(std::mutex* mutex)
{
auto fun = [&]{
std::lock_guard<std::mutex> lock(*mutex);
if(g_count > 0){
cout <<"fun_count2:"<<--g_count<<endl;
}
};
while(g_count > 0){
fun();
usleep(1000*500);
}
}
std::mutex mutex;
std::thread th1(fun_count1,&mutex);
std::thread th2(fun_count2,&mutex);
th1.join();
th2.join();