boost::mutex 无法帮助避免C++程序中的竞争条件
boost::mutex cannot help avoid race conditions in a C++ program ?
我正在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 值。有很多方法可以让主线程等到子线程完成,即
等待任务在线程池中完成
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 在使用 std::cout 和多线程程序中如何避免数据竞争<iomanip>?
- boost::mutex 无法帮助避免C++程序中的竞争条件
- 在c++程序核心转储的反向竞争中,无限中止()
- 在C#程序中避免这种竞争条件
- 在我没有源代码但可以加载 DLL 的程序中导致竞争条件?
- thread程序会导致很多竞争条件