std::try_lock
STD:试一试[医]锁
Defined in header | | |
---|---|---|
template< class Lockable1, class Lockable2, class... LockableN> int try_lock( Lockable1& lock1, Lockable2& lock2, LockableN&... lockn | | (since C++11) |
试图锁定每个给定的Lockable
对象lock1
,,,lock2
,,,...
,,,lockn
打电话try_lock
从第一个开始。
如果打电话到try_lock
失败了unlock
对于任何锁定对象和0
-返回未能锁定的对象的基于索引的索引。
如果打电话到try_lock
结果是一个例外,unlock
在重新抛出之前,对任何锁定对象调用。
参数
lock1, lock2, ... , lockn | - | the Lockable objects to lock |
---|
返回值
-1
关于成功,或0
-未能锁定的对象的基于索引的值。
例
下面的示例使用std::try_lock
定期计数和重置在单独线程中运行的计数器。
二次
#include <mutex>
#include <vector>
#include <thread>
#include <iostream>
#include <functional>
#include <chrono>
int main()
{
int foo_count = 0;
std::mutex foo_count_mutex;
int bar_count = 0;
std::mutex bar_count_mutex;
int overall_count = 0;
bool done = false;
std::mutex done_mutex;
auto increment = [](int &counter, std::mutex &m, const char *desc) {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(m
++counter;
std::cout << desc << ": " << counter << '\n';
lock.unlock(
std::this_thread::sleep_for(std::chrono::seconds(1)
}
};
std::thread increment_foo(increment, std::ref(foo_count),
std::ref(foo_count_mutex), "foo"
std::thread increment_bar(increment, std::ref(bar_count),
std::ref(bar_count_mutex), "bar"
std::thread update_overall([&]() {
done_mutex.lock(
while (!done) {
done_mutex.unlock(
int result = std::try_lock(foo_count_mutex, bar_count_mutex
if (result == -1) {
overall_count += foo_count + bar_count;
foo_count = 0;
bar_count = 0;
std::cout << "overall: " << overall_count << '\n';
foo_count_mutex.unlock(
bar_count_mutex.unlock(
}
std::this_thread::sleep_for(std::chrono::seconds(2)
done_mutex.lock(
}
done_mutex.unlock(
}
increment_foo.join(
increment_bar.join(
done_mutex.lock(
done = true;
done_mutex.unlock(
update_overall.join(
std::cout << "Done processing\n"
<< "foo: " << foo_count << '\n'
<< "bar: " << bar_count << '\n'
<< "overall: " << overall_count << '\n';
}
二次
可能的产出:
二次
bar: 1
foo: 1
foo: 2
bar: 2
foo: 3
overall: 5
bar: 1
foo: 1
bar: 2
foo: 2
bar: 3
overall: 10
bar: 1
foo: 1
bar: 2
foo: 2
overall: 14
bar: 1
foo: 1
bar: 2
overall: 17
foo: 1
bar: 1
foo: 2
overall: 20
Done processing
foo: 0
bar: 0
overall: 20
二次
另见
lock (C++11) | locks specified mutexes, blocks if any are unavailable (function template) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。