gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:12:02 29 4
gpt4 key购买 nike

我正在使用带有 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 中调用的成员函数的指针为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42715305/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com