C++11 介绍 mutex(互斥)
2014-01-19
首先看mutex头文件里面有的内容,如下表:
Classes | |
Mutexes | |
mutex | Mutex class (class ) |
recursive_mutex | Recursive mutex class (class ) |
timed_mutex | Timed mutex class (class ) |
recursive_timed_mutex | Recursive timed mutex (class ) |
Locks | |
lock_guard | Lock guard (class template ) |
unique_lock | Unique lock (class template ) |
Other types | |
once_flag | Flag argument type for call_once (class ) |
adopt_lock_t | Type of adopt_lock (class ) |
defer_lock_t | Type of defer_lock (class ) |
try_to_lock_t | Type of try_to_lock (class ) |
Functions | |
try_lock | Try to lock multiple mutexes (function template ) |
lock | Lock multiple mutexes (function template ) |
call_once | Call function once (public member function ) |
---------------------------------------------------------------------------
mutex类
Mutex class
A mutex is a lockable object that is designed to signal
when critical sections of code need exclusive access, preventing other threads
with the same protection from executing concurrently and access the same memory
locations.
mutex objects provide exclusive ownership and do not support recursivity (i.e., a thread shall not lock a mutex it already owns) -- see recursive_mutex for an alternative class that does.
It is guaranteed to be a standard-layout class.
(constructor) | Construct mutex (public member function ) |
lock | Lock mutex (public member function ) |
try_lock | Lock mutex if not locked (public member function ) |
unlock | Unlock mutex (public member function ) |
native_handle | Get native handle (public member function ) |
从Menber functions说起:
(constructor) 构造函数 负责线程对象的初始化构造。
lock 锁互斥变量。
try_lock 尝试锁互斥变量。
unlock 解锁互斥变量。
native_handle 返回当前句柄,句柄指的是一个核心对象在某一个进程中的唯一索引。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103#include <iostream>
#include <thread>
#include <mutex>
#include <windows.h>
using
namespace
std;
mutex mtx;
// 定义了一个互斥量 mtx
// -------------lock()-----------------------
void
print_block(
int
n,
char
c) {
// 定义了一个临界区,意味着mtx上了锁,独占访问(单独占有这个区域,并且只有此区域可以访问区域内的数据)
mtx.lock();
for
(
int
i = 0; i<n; ++i) { std::cout << c; }
cout <<
‘\n‘
;
mtx.unlock();
}
void
main_print_block()
{
std::
thread
th1(print_block, 50,
‘*‘
);
std::
thread
th2(print_block, 50,
‘$‘
);
th1.join();
th2.join();
}
volatile
int
sum(0);
void
attempt_20k_increases()
{
for
(
int
i = 0; i<20000; ++i)
{
if
(1)
{
// 上锁操作
mtx.lock();
++sum;
mtx.unlock();
}
}
}
void
main_attempt_lock()
{
thread
threads[10];
// 产生10个线程
for
(
int
i = 0; i<10; ++i)
threads[i] =
thread
(attempt_20k_increases);
for
(
auto
& th : threads)
th.join();
cout << sum <<
" successful increases of the counter.\n"
;
}
// -------------try_lock()-----------------------
// ----如果能上锁,就执行区域内代码,否则pass--
void
print_thread_id(
int
id) {<br> sleep(50)
if
(mtx.try_lock()){
cout <<
"thread "
<< id <<
‘\n‘
;
mtx.unlock();
}<br>
else
<br> cout <<
"not running thread "
<< id << endl;<br>
}
void
main_lock()
{
thread
threads[10];
for
(
int
i = 0; i<10; ++i)
threads[i] =
thread
(print_thread_id, i + 1);
for
(
auto
& th : threads)
th.join();
}
volatile
int
counter(0);
void
attempt_10k_increases()
{
for
(
int
i = 0; i<10000; ++i)
{
if
(mtx.try_lock())
{
++counter;
mtx.unlock();
}
}
}
void
main_attempt()
{
thread
threads[10];
for
(
int
i = 0; i<10; ++i)
threads[i] =
thread
(attempt_10k_increases);
for
(
auto
& th : threads)
th.join();
cout << counter <<
" successful increases of the counter.\n"
;
}
void
main()
{
cout <<
"演示 lock()"
<< endl;
main_print_block();
cout << endl;
cout <<
"演示 lock()"
<< endl;
main_attempt_lock();
cout << endl;
cout <<
"演示 try_lock()"
<< endl;
main_lock();
cout << endl;
cout <<
"演示 try_lock()"
<< endl;
main_attempt();
cout << endl;
}
这个例子中显示,列出了2个关于lock(),2个关于unlock()的例子。
lock()的意思是,锁上mtx,才可以执行区域内代码。(unclear)
try_lock()的意思是,如果mtx是上锁的状态,就执行区域内代码,否则跳过此区域,执行下面顺序的代码。
代码执行结果:演示 lock()
**************************************************
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$演示 lock()
200000 successful increases of the counter.演示 try_lock()
not running thread 4
not running thread 5
not running thread 8
not running thread 9
not running thread 2
not running thread 10
not running thread 7
thread 6
not running thread 1
not running thread 3演示 try_lock()
18702 successful increases of the counter.请按任意键继续. . .
---------------------------------------------------------------------------
recursive_mutex类
Recursive mutex class
A recursive mutex is a lockable object, just like
mutex, but allows the same thread to acquire multiple levels of ownership over
the mutex object.
This allows to lock (or try-lock) the mutex object from a thread that is already locking it, acquiring a new level of ownership over the mutex object: the thread will remain locked until member unlock is called as many times as this level of ownership.
It is guaranteed to be a standard-layout class.
(constructor) | Construct recursive mutex (public member function ) |
lock | Lock recursive mutex (public member function ) |
try_lock | Lock recursive mutex if not locked (public member function ) |
unlock | Unlock recursive mutex (public member function ) |
native_handle | Get native handle (public member function ) |
从Menber functions说起:
(constructor) 构造函数 负责线程对象的初始化构造。
lock 锁互斥变量。
try_lock 尝试锁互斥变量。
unlock 解锁互斥变量。
native_handle 返回当前句柄,句柄指的是一个核心对象在某一个进程中的唯一索引。
---------------------------------------------------------------------------
timed_mutex类
Timed mutex class
A timed mutex is a time lockable object that is designed
to signal when critical sections of code need exclusive access, just like a
regular mutex, but additionally supporting timed try-lock requests.
As such, a timed_mutex has two additional members: try_lock_for and try_lock_until.
It is guaranteed to be a standard-layout class.
---------------------------------------------------------------------------
recursive_timed_mutex类
Recursive timed mutex
A recursive timed mutex combines both the features
of recursive_mutex and the features of timed_mutex into a single class: it
supports both acquiring multiple lock levels by a single thread and also timed
try-lock requests.
It is guaranteed to be a standard-layout class.
---------------------------------------------------------------------------
lock_guard类
Lock guard
A lock guard is an object that manages a mutex object by
keeping it always locked.
On construction, the mutex object is locked by the calling thread, and on destruction, the mutex is unlocked. It is the simplest lock, and is specially useful as an object with automatic duration that lasts until the end of its context. In this way, it guarantees the mutex object is properly unlocked in case an exception is thrown.
Note though that the lock_guard object does not manage the lifetime of the mutex object in any way: the duration of the mutex object shall extend at least until the destruction of the lock_guard that locks it.
---------------------------------------------------------------------------
unique_lock类
Unique lock
A unique lock is an object that manages a mutex object with
unique ownership in both states: locked and unlocked.
On construction (or by move-assigning to it), the object acquires a mutex object, for whose locking and unlocking operations becomes responsible.
The object supports both states: locked and unlocked.
This class guarantees an unlocked status on destruction (even if not called explicitly). Therefore it is especially useful as an object with automatic duration, as it guarantees the mutex object is properly unlocked in case an exception is thrown.
Note though, that the unique_lock object does not manage the lifetime of the mutex object in any way: the duration of the mutex object shall extend at least until the destruction of the unique_lock that manages it.
---------------------------------------------------------------------------
Functions
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。