1,317
社区成员
发帖
与我相关
我的任务
分享
#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;
}