我正在摆弄 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