boost::mutex 无法帮助避免C++程序中的竞争条件

boost::mutex cannot help avoid race conditions in a C++ program ?

本文关键字:程序 竞争 条件 C++ mutex 帮助 boost      更新时间:2023-10-16

我正在Linux上做一个多线程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 ;
 }

任何帮助将不胜感激。

谢谢!

来自 http://threadpool.sourceforge.net/tutorial/intro.html :

了解任务仅安排在 执行。立即安排退货,没有保证 关于任务的执行时间和处理时间 拿。

安排 10 个任务,然后立即打印结果,直到您到达生产线时执行的尽可能多的任务

std::cout <<g <<std::endl ;

因此,虽然您的互斥锁确保线程一次递增一个 g,但您不会等待它们完成才打印结果。修改代码的一种方法是等待池中的所有任务完成:

boost::threadpool::fifo_pool tp(threadnum);
for (int i = 0 ; i < threadnum ; ++i)
        tp.schedule(boost::bind(f));
tp.wait(); //WAIT FOR TASKS TO EXECUTE
std::cout << g << std::endl ;
return 0 ;

我不确定我是否正确阅读了这篇文章,但看起来您正在安排一堆会增加 g 的事情,然后在 g 的内容上调用 cout。 您的互斥锁可以防止计划的进程相互践踏,但没有什么会迫使最后的 cout 等到它们全部完成。 为此,您需要某种读/写互斥锁。

似乎主线程在子线程之前完成 - 这就是为什么你会得到看似随机的 g 值。有很多方法可以让主线程等到子线程完成,即

等待任务在线程池中完成