gpt4 book ai didi

c++ - try_lock_for 未按预期工作

转载 作者:可可西里 更新时间:2023-11-01 18:36:03 26 4
gpt4 key购买 nike

我正在摆弄一些 C++ 中的代码,由于某种原因不想工作,我将它缩小到这种情况:

#include <thread>
#include <atomic>
#include <chrono>
#include <mutex>
#include <iostream>

using namespace std;

void test()
{
timed_mutex m;
m.lock();
std::cout << "Can i have the lock? " << m.try_lock() << std::endl;
std::cout << "in test(), should block for 10 seconds" << std::endl;
bool got_lock = m.try_lock_for(std::chrono::seconds(10));
std::cout << "Now i've blocked, got the lock: " << got_lock << std::endl;
m.unlock();
}

int main()
{
thread t = thread(&test);
t.join();

return EXIT_SUCCESS;
}

问题是 test() 根本不会阻塞,即使 try_lock 返回 false。有没有我忽略的东西,或者这是 gcc 中的错误,或者我接下来应该去哪里找出问题所在?感谢任何建议和帮助!

我像这样编译了这个小程序:g++ -pthread -std=c++11 threads.cpp -o threads如果有任何帮助,这是 gcc 和我的操作系统的版本:

g++ --version
g++ (GCC) 4.7.2
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

uname -a
Linux *computername* 3.6.11-1-ARCH #1 SMP PREEMPT Tue Dec 18 08:57:15 CET 2012 x86_64 GNU/Linux

最佳答案

您的代码行为未定义。 std::timed_mutex 具有非递归所有权 语义。禁止在同一个线程上第二次获取锁(包括try_lock家族)。

C++11 标准 30.4.1.3.1 [thread.timedmutex.class]/p3/b2:(感谢 Howard Hinnant)

3 The behavior of a program is undefined if:

  • a thread that owns a timed_mutex object calls lock(), try_lock(), try_lock_for(), or try_lock_until() on that object, or

C++11 标准 30.4.1.2 [thread.mutex.requirements.mutex]/p6-7:


已编辑:

how i am going to "work around this" or get it to behave the way i want? Should i use a recursive mutex instead?

一般来说,出于异常安全的考虑,不鼓励获取/释放互斥对象的锁。如果您改用 unique_lock 对象,owns_lock() 成员函数可能会帮助您。同时,递归互斥锁对您的目的毫无用处,因为“递归”仅意味着“我(一个线程)在我已经拥有锁时可以获得两次或更多次锁。”

void test()
{
std::timed_mutex m;
std::unique_lock<decltype(m)> lk(m, std::defer_lock);

// acquire lock
lk.lock();
// You can query locked status via unique_lock object
std::cout << "Do I have own lock? " << lk.owns_lock() << std::endl;
// release lock
lk.unlock();
}

关于c++ - try_lock_for 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14413211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com