我正在Linux上进行多线程C++ boost。boost :: mutex无法避免C++程序中的竞争条件?
即使我尝试使用锁,以下程序仍然存在竞态条件。
结果是8或9或5。它不应该发生。
#include <iostream>
#include <boost/bind.hpp>
#include <boost/threadpool.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>
boost::mutex myMutex ;
int g = 0 ;
void f()
{
//myMutex.lock();
{
boost::mutex::scoped_lock lock(myMutex);
++g;
}
//myMutex.unlock();
return ;
}
const int threadnum = 10;
int main()
{
boost::threadpool::fifo_pool tp(threadnum);
for (int i = 0 ; i < threadnum ; ++i)
tp.schedule(boost::bind(f));
std::cout << g << std::endl ;
return 0 ;
}
任何帮助将不胜感激。
谢谢!
不应该等待线程停止吗? – mfontanini
唯一可以防止竞争条件或死锁的是**正确的设计**。没有银弹。 –
我还会补充说,在主返回之前,任务**确实已经完成了**:它是超出范围之前完成所有任务并且可以更改的默认关闭策略。只是他们没有完成...... std :: cout ...执行。 –