c++ 11 多线程编程--互斥体类(2)

接   c++ 11 多线程编程--互斥体类(1)
(2)std::recursive_mutex
        std::recursive_mutex的行为几乎和std::mutex一致,区别在于已经获得一个递归互斥体所有权的线程允许在同一个互斥体再次调用lock()和try_lock()。但调    用unlock()方法的次数应该等于获得这个递归互斥体锁的次数。

(3)std::temed_mutex类与std::recursive_timed_mutex类
         两个类都支持lock()、try_lock()、unlock()方法。还支持特有的俩个方法:
         1 try_lock_for(rel_time)。调用线程将尝试在一个给定的相对时间内试图获得这个锁。如果不能再给定的时间之内获得这个锁,则返回false,如果在给定时间类获得这个锁返回true
         2  try_lock_until(abd_time)。调用线程将尝试获得这个锁,直到系统时间等于或超过给定的绝对时间。如果在改绝对时间之前获得锁返回true,如果系统时间超过给定的时间。则不再尝试并返回false。 
     
// timed_mutex类.cpp : 定义控制台应用程序的入口点。
// timed_mutex::try_lock_for example
#include "stdafx.h"

#include <iostream>       // std::cout
#include <chrono>         // std::chrono::milliseconds
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex

std::timed_mutex mtx;

void fireworks()
{
               
       // waiting to get a lock: each thread prints "-" every 200ms:
         while (!mtx.try_lock_for(std::chrono::milliseconds(200)))//200ms
          {
            std::cout << "-";
          }
        // got a lock! - wait for 1s, then this thread prints "*"
          std::this_thread::sleep_for(std::chrono::milliseconds(1000));
          std::cout << "*\n";
          mtx.unlock();
}

int main()
{
       std::thread threads[10];
       // spawn 10 threads:
        for (int i = 0; i<10; ++i)
        threads[i] = std::thread(fireworks);

        for (auto& th : threads) th.detach();
        return 0;
}
/*输出结果*/
/*
*
----*
----------------------------*
------------------------------*
-------------------------*
--------------------*
----------------*
----------*
-------*
*
*/
std::recursive_timed_mutex的行为几乎和std::timed_mutex一致,区别在于已经获得一个递归互斥体所有权的线程允许在同一个互斥体再次调用lock()和try_lock()。但调用unlock()方法的次数应该等于获得这个递归互斥体锁的次数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值