您的位置:首页 > 编程语言 > C语言/C++

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

2016-08-31 13:36 323 查看
接   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()方法的次数应该等于获得这个递归互斥体锁的次数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 多线程