Boost strand 和 io_service 调度问题?

海洋小屋 2016-08-31 10:01:29
先贴上代码
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <thread>
#include <mutex>
#include <unistd.h>

boost::asio::io_service m_service;
boost::asio::io_service::strand m_strand(m_service);
std::mutex mtx;

void print(int id){
//mtx.lock();
//std::cout<<std::endl<<std::this_thread::get_id()<<std::endl;
static int cnt = 0;
std::cout<<"id: "<<id<<std::endl;
++cnt;
std::cout<<"count: "<<cnt<<std::endl;
//mtx.unlock();
}

void Run1(){
int ret = m_service.run_one();
std::cout<<"Run1 excute "<<ret<<" Handlers."<<std::endl;
}
void Run2(){
int ret = m_service.run_one();
std::cout<<"Run2 excute "<<ret<<" Handlers."<<std::endl;
}


void print1(){
m_strand.dispatch(m_strand.wrap(std::bind(print, 1)));
}

void print2(){
m_strand.post(m_strand.wrap(std::bind(print, 2)));
}

void print3(){
m_strand.post(m_strand.wrap(std::bind(print, 3)));
}

void print4(){
m_strand.post(m_strand.wrap(std::bind(print, 4)));
}

void test(){
std::thread t1(print1);
std::thread t2(print2);
std::thread t3(print3);
std::thread t4(print4);

//std::thread ios1(Run1);
//std::thread ios2(Run2);

t1.join();
t2.join();
t3.join();
t4.join();

//ios1.join();
//ios2.join();

int ret = m_service.run();
std::cout<<"Main thread excute "<<ret<<" Handlers."<<std::endl;
}

int main(int argc, const char ** argv){
try{
test();
}
catch(std::exception& e){
std::cout<<e.what()<<std::endl;
}
return 0;
}


编译上面的代码, 主进程在 test函数中调用m_service.run() 函数,可以执行四个Handler,但是返回值确实 2,不是应该返回4?求解???

另一个问题,当我多开两个线程来调用 m_service.run_one() 的时候,偶尔会出现一种情况, 主进程的run返回值为0, 另外调用run_one()函数的两个线程,都会回 1, 但是通过打印线程ID发现, 这两个返回1 的线程,一个执行了一个Handler, 另外一个确执行了 3个 handler,主进程一个未执行, 这是怎么回事??????(初学者,发现这个问题,略迷茫,求大神指教,再次先谢过!)
...全文
1564 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

1,316

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder 网络及通讯开发
社区管理员
  • 网络及通讯开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧