【发布时间】:2020-08-02 07:50:29
【问题描述】:
我正在尝试创建一个包含 boost::thread 对象的简单结构。这个结构(ApplicationPair)的构造函数需要传递一个io_service引用对象和一个方法;现在,为简单起见,我使用的是不带参数的 void 方法。 之后,使用 boost::bind 创建线程。
ApplicationPair.h
#ifndef APPLICATIONPAIR_H
#define APPLICATIONPAIR_H
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <cstdarg>
template<typename T>
struct ApplicationPair
{
ApplicationPair(boost::asio::io_service& iSvc, boost::function<T()> func ) : _func(func)
{
iSvc.post(boost::bind(&ApplicationPair<T>::run, this));
thr = boost::thread(boost::bind(&boost::asio::io_service::run, &iSvc));
}
ApplicationPair() = delete;
~ApplicationPair() { if (thr.joinable()) thr.join(); }
void run();
boost::thread thr;
boost::function<T()> _func;
};
#endif
这里的想法是,我创建的每个新 ApplicationPair 对象都将在 io_service 上拥有自己的线程,并在实例化时启动我想要的任何方法。
这里是主要的:
main.cpp
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <cstdio>
boost::asio::io_service iSvc;
void HelloWorld()
{
std::cout << "HelloWorld\n";
}
template<typename T>
void ApplicationPair<T>::run()
{
this->_func();
}
int main()
{
ApplicationPair<void> p1(boost::ref(iSvc), HelloWorld);
ApplicationPair<void> p2(boost::ref(iSvc), HelloWorld);
ApplicationPair<void> p3(boost::ref(iSvc), HelloWorld);
return 0;
}
这就是我意识到事情进展得很糟糕的地方:我的预期输出是 3 个“HelloWorld”打印,但我只得到 2 个。 更奇怪的是,如果我运行调试,并逐条执行进一步的指令,HelloWorld 只会打印一次!
老实说,我一无所知,但我很清楚我并没有完全理解多线程和 io_services 的工作原理,而且 Boost.org 上的文档根本没有帮助。
【问题讨论】:
标签: c++ multithreading boost asio