io_context.stop 后不要调用 io_context.reset

io_context.reset 内部会把 stopped_ 变量设置成 0,也就是没有 stop 的意思。
等到 io_context.run 判断的时候就不会返回。

#include <thread>
#include <boost/asio.hpp>

#include <boost/asio/io_context.hpp>
#include <iostream>
#include <memory>
#include <Windows.h>

using namespace std;
using namespace boost;

namespace net = boost::asio;

using boost::asio::ip::tcp;

net::io_context ioc;
net::io_context::work work(ioc);

thread g_thread;

void foo();

void bar()
{
  cout << "bar before sleep" << endl; // 当打印这行后,立刻按 Ctrl+C
  this_thread::sleep_for(3s);
  cout << "bar after sleep" << endl;

  ioc.reset();

  tcp::socket s(ioc);
  tcp::endpoint ep(boost::asio::ip::address_v4::from_string("127.0.0.1"), 9999);

  s.async_connect(ep, [](const boost::system::error_code& error) {
    cout << "connect callback error: " << error << endl;
    ioc.post(foo);
    });
}

void foo()
{
  // 如果换成 thread 调用 bar,io_context 就可以退出。
  //thread t([]() {
  //  bar();
  //});
  //t.detach();

  bar();
}

void io_thread()
{
  ioc.run();

  cout << "after ioc.run" << endl;
}

BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
{
  ioc.stop();
  cout << "ios stop" << endl;
  g_thread.join();
  return FALSE;
}

int main(int argc, char* argv[])
{
  SetConsoleCtrlHandler(CtrlHandler, TRUE);

  g_thread = thread(io_thread);
  
  ioc.post(foo);

  //for (;;)
  //{
  //  this_thread::sleep_for(10s);
  //}
  //this_thread::sleep_for(10s);

  //ioc.stop();
  //cout << "ioc stop" << endl;

  //this_thread::sleep_for(30s);
  return 0;
}

在 bar 函数中,当输出 bar before sleep 的时候,按下 Ctrl+C,那么 io_context 拥有不会 stop。因为 bar 函数紧接着会调用 io_context.reset。

但是如果把 foo 函数中调用 bar 换成 thread 方式。那么用上边同样的流程,io_context 会正常停下来。还不知道什么原因,具体原因有待研究。

win10 x64 boost 1.70.0

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值