标签:
mutex mutexclass(class)
recursive_mutex Recursivemutex class(class)
time_mutex Timedmutex class(class)
recursive_timed_mutex Recursivetimed murex(class)
lock_guard Lock_guard(classtemplate)
unique_lock Unique_lock(classtemplate)
once_flag Flagargument type for call_once(class)
adopt_lock_t Typeof adopt_lock(class)
defer_lock_t Typeof defer_lock(class)
try_to_lock_t Typeof try_to_lock(class)
try_lock Try to lock multiplemutexes(function template)
lock Lockmultiple muteses(function template)
call_once Callfunction once(public member function)
Mutex是一个互斥锁对象,当某线程需要对资源独占访问时,阻止需要独占访问相同资源的其他线程同时对资源进行访问。
(constructor) Constructmutex(public member function)
Lock Lock mutex(publicmember function)
try_lock Lockmutex if not locked(public member function)
unlock Unlockmutex(public member function)
native_handle Getnative handle(public member function)
#include <iostream> #include <thread> #include <mutex> std::mutexmtx; //定义全局互斥量 void fucOne(intn, charc) {//用mutex对std::cout signal 独占访问 mtx.lock(); for(int i = 0; i < n;++i) { std::cout<< c; } std::cout<< std::endl; mtx.unlock(); } int main(int argc,_TCHAR* argv[]) { std::thread th1(fucOne, 50, '#'); std::thread th2(fucOne, 50, '$'); std::thread th3(fucOne, 50, '%'); std::thread th4(fucOne, 50, '^'); th1.join(); th2.join(); th3.join(); th4.join(); return0; }
std::recursive_mutex 与 std::mutex 对象一样,都是一种可以上锁的对象,且成员函数相同。与std::mutex不同的是,std::recursive允许同一个线程对互斥量多次上锁(即递归上锁),以获取互斥量的多层所有权。std::recursive_mutex释放互斥量时需要调用与该锁递归深度相同次数的std::recursive_mutex::unlock()。即lock()次数与unlock()次数相同,除此之外,其与std::mutex用法大致相同。
(constructor) Constructmutex(public member function)
Lock Lock mutex(publicmember function)
try_lock Lockmutex if not locked(public member function)
try_lock_for Tryto lock for time span(public member function)
try_lock_until Tryto lock until time point(public member function)
unlock Unlockmutex(public member function)
native_handle Getnative handle(public member function)
try_lock_for用法说明:其接受一个时间范围,表示在这一段时间范围之内线程如果没有获得锁则被阻塞住(与std::mutex::try_lock不同,try_lock被调用时如果没有获得锁,直接返回false),如果在此期间其他线程获得了锁,则线程可获得互斥量的锁,如果超时(在指定时间内没有获得锁),返回false
try_lock_until用法说明:其接受一个时间点作为参数,在指定时间点未到来之前线程如果没有获得锁则被阻塞,如果在此期间其他线程释放了锁,则该线程可获得互斥量的锁,如果超时(在指定时间点到来之前没有获得锁),返回false
#include <iostream> #include <chrono> #include <thread> #include <mutex> std::timed_mutextime_mtx; voidfireWorks() { //等待获取互斥锁期,每200ms输出字符‘-’ while(!time_mtx.try_lock_for(std::chrono::milliseconds(200))) { std::cout<< "-"; } //获取到互斥锁时,此线程睡眠1s之后输出字符“*”并换行 std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::cout<< "*" << std::endl; //解锁 time_mtx.unlock(); } int main(int argc,_TCHAR* argv[]) { std::thread threads[10]; //为每个线程绑定函数fireWorks for(auto&th:threads) { th= std::thread(fireWorks); } for(auto&th : threads) { th.join(); } return0; }
std::recusive_timed_mutex与std::timed_mutex的关系跟std::recursive_mutex与std::mutex的关系一样,这里不多做介绍。
标签:
原文地址:http://blog.csdn.net/u013507368/article/details/45073549