std::lock
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <mutex> 中定义
|
||
template< class Lockable1, class Lockable2, class LockableN... > void lock( Lockable1& lock1, Lockable2& lock2, LockableN& lockn... ); |
(C++11 起) | |
。
锁定给定的
Lockable
对象lock1
,lock2
,...
,lockn
使用,以避免死锁的避免死锁的算法.原文:
Locks the given
Lockable
objects lock1
, lock2
, ...
, lockn
using a deadlock avoidance algorithm to avoid deadlock.。锁定对象未指定的调用
lock
,try_lock
,unlock
。如果lock
或unlock
,将引发异常,unlock
被称为任何被锁定的对象,然后重新抛出.原文:
The objects are locked by an unspecified series of calls to
lock
, try_lock
, unlock
. If a call to lock
or unlock
results in an exception, unlock
is called for any locked objects before rethrowing.[编辑] 。参数。
lock1, lock2, ... , lockn | - | 。
Lockable 对象锁定。 |
===。 返回值。===
。 (无)。
[编辑] 。为例。
。下面的示例使用
std::lock
对互斥对象锁定无死锁.
原文:
The following example uses
std::lock
to lock pairs of mutexes without deadlock.
#include <mutex> #include <thread> #include <iostream> #include <vector> #include <functional> #include <chrono> struct Employee { Employee(int id) : id(id) {} int id; std::vector<int> lunch_partners; std::mutex m; }; void send_mail(Employee &e1, Employee &e2) { // simulate a time-consuming messaging operation std::this_thread::sleep_for(std::chrono::seconds(1)); } void assign_lunch_partner(Employee &e1, Employee &e2) { // use std::lock to acquire two locks without worrying about // other calls to assign_lunch_partner deadlocking us std::lock(e1.m, e2.m); e1.lunch_partners.push_back(e2.id); e2.lunch_partners.push_back(e1.id); e1.m.unlock(); e2.m.unlock(); send_mail(e1, e2); send_mail(e2, e1); } int main() { Employee alice(0), bob(1), christina(2), dave(3); // assign in parallel threads because mailing users about lunch assignments // takes a long time std::vector<std::thread> threads; threads.emplace_back(assign_lunch_partner, std::ref(alice), std::ref(bob)); threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(bob)); threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(alice)); threads.emplace_back(assign_lunch_partner, std::ref(dave), std::ref(bob)); for (auto &thread : threads) thread.join(); }
[编辑] 。另请参阅。
(C++11) |
通过重复调用 try_lock 试图获得互斥体的所有权 原文: attempts to obtain ownership of mutexes via repeated calls to try_lock (函数模板) |