try_lock_for无法正常工作

lfx*_*ove 7 c++ multithreading mutex locking c++11

我正在摆弄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;
}
Run Code Online (Sandbox Code Playgroud)

问题是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
Run Code Online (Sandbox Code Playgroud)

yoh*_*hjp 6

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

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

3如果出现以下情况,程序的行为是不确定的:

  • 拥有一个线程timed_mutex对象的调用lock(),try_lock(),try_lock_for(),或try_lock_until()在该对象上,或

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


编辑:

我将如何"解决这个问题"或让它按照我想要的方式行事?我应该使用递归互斥体吗?

一般来说,根据异常安全情况,不鼓励获取/释放互斥锁对象的锁定.如果您使用unique_lock对象,owns_lock()成员函数可能会帮助您.同时recursive-mutex对你的目的没用,因为"递归"只意味着"当我已经拥有锁定时,我(一个线程)可以获得两次或更多次的锁定."

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();
}
Run Code Online (Sandbox Code Playgroud)

  • +1正确答案错误的报价.30.4.1.3.1 [thread.timedmutex.class]/p3/b2:拥有`timed_mutex`对象的线程调用`lock()`,`try_lock()`,`try_lock_for()`或`try_lock_until() `在那个物体上, (2认同)