Namespaces
Variants

std:: try_lock

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
try_lock
(C++11)
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
定义于头文件 <mutex>
template < class Lockable1, class Lockable2, class ... LockableN >
int try_lock ( Lockable1 & lock1, Lockable2 & lock2, LockableN & ... lockn ) ;
(C++11 起)

尝试按顺序从第一个开始,通过调用 try_lock 来锁定给定的每个 Lockable 对象 lock1 lock2 ... lockn

如果对 try_lock 的调用失败,则不会继续执行后续的 try_lock 调用,系统会为所有已锁定的对象调用 unlock ,并返回基于 0 的锁定失败对象索引。

如果对 try_lock 的调用导致异常,将在重新抛出异常前对所有已锁定的对象调用 unlock

目录

参数

lock1, lock2, ..., lockn - 待锁定的 Lockable 对象

返回值

- 1 表示成功,或返回 0 起始的锁定失败对象索引值。

示例

以下示例使用 std::try_lock 定期统计并重置运行在独立线程中的计数器。

#include <chrono>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
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

参见

(C++11)
锁定指定的互斥量,若任一不可用则阻塞
(函数模板)