我正在研究 Boost Threads 和 Asio(异步输入/输出),并编写了以下示例以将一些概念放在一起。
class Worker {
private:
boost::asio::io_service& m_ios;
boost::asio::deadline_timer m_timer;
unsigned m_cycles;
unsigned m_time2wait;
std::string m_threadName;
public:
Worker(boost::asio::io_service& ios,
unsigned cycles, unsigned time2wait, const std::string& name);
~Worker ();
void start ();
void run ();
void stop ();
};
Worker::Worker (boost::asio::io_service& ios,
unsigned cycles, unsigned time2wait, const std::string& name)
: m_ios(ios),
m_timer(ios, boost::posix_time::seconds (1)),
m_cycles(cycles),
m_time2wait(time2wait),
m_threadName(name)
{
logMsg(m_threadName, "is starting . . . ");
}
Worker::~Worker()
{
logMsg(m_threadName, "is ending . . . ");
}
void Worker::start()
{
logMsg (m_threadName, "start was called");
m_timer.expires_at (m_timer.expires_at () +
boost::posix_time::seconds (m_time2wait));
m_timer.async_wait (boost::bind (&Worker::run, this));
}
void Worker::stop()
{
}
void Worker::run()
{
if (m_cycles > 0)
{
logMsg (m_threadName, "run # ", m_cycles);
--m_cycles;
m_timer.expires_at (m_timer.expires_at() +
boost::posix_time::seconds(m_time2wait));
m_timer.async_wait(boost::bind(&Worker::run, this));
}
else {
logMsg (m_threadName, "end of cycling");
}
}
void run_threads (boost::asio::io_service& io_srv)
{
Worker worker_1(io_srv, 5, 2, "worker 1");
Worker worker_2(io_srv, 5, 4, "worker 2");
worker_1.start();
worker_2.start();
boost::shared_ptr <boost::thread> worker_Thread_One (
new boost::thread (boost::bind (&boost::asio::io_service::run, &io_srv)));
boost::shared_ptr <boost::thread> worker_Thread_Two (
new boost::thread(boost::bind(&boost::asio::io_service::run, &io_srv)));
worker_Thread_One->join();
worker_Thread_Two->join();
}
int main (int argc, char** argv)
{
boost::asio::io_service ios;
run_threads(ios);
return 0;
}
我试图让一些线程并行工作,每个线程都通过一个特定的对象完成它的工作。该示例显然似乎有效,但我感觉混合线程和 Asio (糟糕的设计)是错误的。让线程与 Asio 一起工作是否正确(一个 io_service 用于多个线程)?
线程对象和“worker”对象是如何“绑定”在一起的?我认为他们不像我想的那样。例如,如果我实例化了两个对象和两个线程,我就有了预期的输出。如果我实例化两个对象和一个线程,则程序的输出是相同的。
(logMsg 是一个简单的 cout 包装器,带有互斥锁以同步输出操作。)