首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::mutex::try_lock

bool try_lock();

?

(since C++11)

试图锁定互斥体。马上回来。关于成功锁定获取返回true,否则返回false...

此函数允许伪造失败并返回。false即使互斥锁目前没有被任何其他线程锁定。

如果try_lock由已经拥有mutex,该行为是未定义的。

优先unlock()对同一个互斥体的操作同步性中定义的28名ASstd::memory_order%29如果返回此操作true.注意到以前lock()如果此操作返回,则不与其同步。false...

参数

%280%29

返回值

true如果成功获取锁,则为false...

例外

%280%29

二次

代码语言:javascript
复制
#include <chrono>
#include <mutex>
#include <thread>
#include <iostream> // std::cout
 
std::chrono::milliseconds interval(100);
 
std::mutex mutex;
int job_shared = 0; // both threads can modify 'job_shared',
    // mutex will protect this variable
 
int job_exclusive = 0; // only one thread can modify 'job_exclusive'
    // no protection needed
 
// this thread can modify both 'job_shared' and 'job_exclusive'
void job_1() 
{
    std::this_thread::sleep_for(interval); // let 'job_2' take a lock
 
    while (true) {
        // try to lock mutex to modify 'job_shared'
        if (mutex.try_lock()) {
            std::cout << "job shared (" << job_shared << ")\n";
            mutex.unlock();
            return;
        } else {
            // can't get lock to modify 'job_shared'
            // but there is some other work to do
            ++job_exclusive;
            std::cout << "job exclusive (" << job_exclusive << ")\n";
            std::this_thread::sleep_for(interval);
        }
    }
}
 
// this thread can modify only 'job_shared'
void job_2() 
{
    mutex.lock();
    std::this_thread::sleep_for(5 * interval);
    ++job_shared;
    mutex.unlock();
}
 
int main() 
{
    std::thread thread_1(job_1);
    std::thread thread_2(job_2);
 
    thread_1.join();
    thread_2.join();
}

二次

可能的产出:

二次

代码语言:javascript
复制
job exclusive (1)
job exclusive (2)
job exclusive (3)
job exclusive (4)
job shared (1)

二次

另见

lock

locks the mutex, blocks if the mutex is not available (public member function)

unlock

unlocks the mutex (public member function)

c MTX文件[医]幽会

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com