c++ - 作为参数给在 boost::thread_group 中调用的成员函数的指针为 null

标签 c++ boost threadpool

我正在使用 C++ 和 boost::thread_group 使用线程池,但在线程中调用方法“widgetProcessorJob”获取空参数(小部件)。 我尝试以不同的方式实现它,我认为我使用 boost::asio 很糟糕...... 我正在寻找可以告诉我做错了什么以及哪种方法是最好的方法的人?

void MarketingAutomation::processOnWidgets() {
    boost::asio::io_service ioService;
    boost::thread_group threadpool;
    bool available = true; // need infinite loop in my program
    int offset = 0; // Only for batching

    boost::asio::io_service::work work(ioService);
    for (int i = 0; i < _poolSize; i++) {
        threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
    }

    while (available) {
        std::shared_ptr<sql::ResultSet> widgets(MyDBConnector::getInstance().getWidgets(_batchSize, offset)); // just getting some data from sql base with mysqlcppconn

        if (!widgets->next()) {
            offset = 0;
            Logger::getInstance().logSTD("Restart widgets iteration !"); // this part is called when i did stuff on all batches
        } else {

            Logger::getInstance().logSTD("Proccess on " + std::to_string((offset / _batchSize) + 1) + " batch");

            // loop through the batch
            while (!widgets->isAfterLast()) {
                ioService.post(boost::bind(&MarketingAutomation::widgetProcessorJob, this, widgets));
                widgets->next();
            }

            threadpool.join_all();
            Logger::getInstance().logSTD("Finish on " + std::to_string((offset / _batchSize) + 1) + " batch");
            offset += _batchSize;

        }
    }
}

// Here is the function called in thread
void MarketingAutomation::widgetProcessorJob(std::shared_ptr<sql::ResultSet> widget) {
    WidgetProcessor widgetProcessor(widget, _kind); // Here widget is already null, but why ? :'(
    widgetProcessor.processOnWidget();
}

最佳答案

// loop through the batch
while (!widgets->isAfterLast()) {
    ioService.post(boost::bind(&MarketingAutomation::widgetProcessorJob, this, widgets));
    widgets->next();
}

您只有一个std::shared_ptr<sql::ResultSet> widgets 。通过多次发布,您将复制智能指针,但所有这些智能指针都指向相同的底层 sql::ResultSet 。 这意味着当您调用 next()您正在“下一个”您发布到所有处理程序的同一记录集。

现在,根据线程的执行时间和不同的竞争条件,您可能在调用任何处理程序之前就已经到达记录集的末尾,即使情况并非如此,您也处于竞争条件中,最多只能得到你想要的一部分。

关于c++ - 作为参数给在 boost::thread_group 中调用的成员函数的指针为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42715305/

相关文章:

c++ - 从 QTextBrowser 打开文件

c++ - 结构包装重复

c - Linux C,如何安排10个等待线程以FIFO方式执行?

c++ - 从文件中获取字符而不是 getchar

C++ 从无符号字符数组创建 GUID

c++ - 使用 boost 读取执行命令的结果(C++ 库)

c++ - 使用 Boost Graph 顶点属性进行动态分配

c++ - 如何为 double 编写一个包装器以与 boost 序列化一起使用?

c# - 需要帮助了解 .net ThreadPool

java - Android线程池管理多个蓝牙处理线程?