https://blog.csdn.net/xiaoliangsky/article/details/23568671
boost::asio学习之[二]boost::asio::strand
2014年04月13日 00:51:38
阅读数:1456
-
#pragma once
-
#include <boost/bind.hpp>
-
#include <boost/thread.hpp>
-
#include <boost/asio.hpp>
-
namespace Strand
-
{
-
using namespace boost::asio;
-
boost::mutex mutex;
-
void io_run(const boost::shared_ptr<io_service>& io)
-
{
-
mutex.lock();
-
std :: cout << "[" << boost::this_thread::get_id() << "] Thread Start" << std::endl ;
-
mutex.unlock();
-
io->run();
-
mutex.lock();
-
std :: cout << "[" << boost::this_thread::get_id() << "] Thread End" << std::endl ;
-
mutex.unlock();
-
}
-
void print_num(int x)
-
{
-
mutex.lock();
-
std :: cout << "[" << boost::this_thread::get_id() << "] x: " << x << std::endl ;
-
mutex.unlock();
-
}
-
/*
-
*我们知道在多条thread的程式设计中,对于执行的结果我们是无法预期的。虽然使用mutex可以保证thread-safety,
-
*但却无法保证工作能够照我们所期望的顺序执行。
-
*在boost ASIO中提供了strand来解决既能保证thread-safety又能够让工作的顺序能够依照post的顺序执行。执行
-
*并观察以下的程式结果:
-
*/
-
void fun_01()
-
{
-
boost::shared_ptr<io_service> io(new io_service);
-
boost::shared_ptr<io_service::work> work(new io_service::work(*io));
-
io_service::strand strand(*io);
-
boost::thread_group group;
-
for (int x = 0 ; x < 2; ++x)
-
{
-
group.create_thread(boost::bind(&io_run, io));
-
}
-
boost::this_thread::sleep(boost::posix_time::seconds(1));
-
/* 按顺序执行
-
strand.post(boost::bind(&print_num, 1));
-
strand.post(boost::bind(&print_num, 2));
-
strand.post(boost::bind(&print_num, 3));
-
strand.post(boost::bind(&print_num, 4));
-
strand.post(boost::bind(&print_num, 5)); */
-
//随机执行
-
io->post(boost::bind(&print_num, 1));
-
io->post(boost::bind(&print_num, 2));
-
io->post(boost::bind(&print_num, 3));
-
io->post(boost::bind(&print_num, 4));
-
io->post(boost::bind(&print_num, 5));
-
work.reset();
-
group. join_all();
-
system ( "pause" ) ;
-
}
-
}