我在尝试处理一些 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的一个bug,或者我应该去哪里找出问题所在?感谢任何建议和帮助!
我像这样编译了这个小程序:
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
real 0m0.004s
。这可能与特定的gcc版本有关。 - Alexandre C.