我正在使用 C++ 开发一个项目。
我希望在指定时间后调用一个 TimerHandler,但同时我不想阻塞当前线程或以下代码中 io.run() 之后的任何代码:
#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class TimerTest
{
public:
static void PrintOutTimerHandler(const boost::system::error_code&, const std::string& message)
{
std::cout << "PrintOutTimerHandler called: " << ", message: " << message << std::endl;
}
void run()
{
boost::asio::io_service io;
boost::asio::deadline_timer dt(io, boost::posix_time::seconds(5));
std::cout << "Start:\t" << std::endl;
dt.async_wait(boost::bind(PrintOutTimerHandler, boost::asio::placeholders::error, std::string("here is the message")));
// Do some job here
for (int i = 0; i < 1000000; ++i)
++i, --i;
std::cout << "End:\t" << std::endl;
io.run();
std::cout << "When to reach here 1: " << std::endl;
}
};
int main()
{
TimerTest tt;
tt.run();
std::cout << "When to reach here 2: " << std::endl;
return 0;
}
/* Current output:
Start:
End:
PrintOutTimerHandler called: , message: here is the message
When to reach here 1:
When to reach here 2:
*/
/* Expected output:
Start:
End:
When to reach here 1:
When to reach here 2:
PrintOutTimerHandler called: , message: here is the message
*/
我想我已经说清楚了。我的问题是:
- 如果不用 引入一个新线程,比如 Flex ActionScript,这是最好的,但是 我猜不是(我猜 ActionScript 是 使用隐藏线程);
- 如果我们不得不 引入一个额外的线程来做 工作,你介意写下 给我的伪代码?
谢谢。
彼得
最佳答案
这是一个例子。在单独的线程中运行 io_service
asio::io_service io_service;
asio::thread t(boost::bind(&asio::io_service::run, &io_service));
或者在线程组中运行
boost::thread_group threads;
for (std::size_t i = 0; i < my_thread_count; ++i)
threads.create_thread(boost::bind(&asio::io_service::run, &io_service));
请记住,您的主线程应该始终运行,因为当它存在时,所有产生的线程也会退出。
希望对您有所帮助。
关于c++ - 如何使用 Boost 库创建 TimerHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6026467/