gpt4 book ai didi

c++ - 从并发析构函数停止 boost::asio::io_service::run()

转载 作者:太空狗 更新时间:2023-10-29 21:37:36 25 4
gpt4 key购买 nike

谁能解释一下为什么这个程序没有终止(见评论)?

#include <boost/asio/io_service.hpp>
#include <boost/asio.hpp>
#include <memory>
#include <cstdio>
#include <iostream>
#include <future>

class Service {
public:
~Service() {
std::cout << "Destroying...\n";
io_service.post([this]() {
std::cout << "clean and stop\n"; // does not get called
// do some cleanup
// ...
io_service.stop();
std::cout << "Bye!\n";
});
std::cout << "...destroyed\n"; // last printed line, blocks
}

void operator()() {
io_service.run();
std::cout << "run completed\n";
}

private:
boost::asio::io_service io_service;
boost::asio::io_service::work work{io_service};
};

struct Test {
void start() {
f = std::async(std::launch::async, [this]() { service(); std::cout << "exiting thread\n";});
}
std::future<void> f;
Service service;
};

int main(int argc, char* argv[]) {
{
Test test;
test.start();

std::string exit;
std::cin >> exit;
}

std::cout << "exiting program\n"; // never printed
}

最佳答案

真正的问题是破坏io_service是(显然)不是线程安全的。

只需重置工作并加入线程即可。 (可选)设置一个标志,以便您的 IO 操作知道正在关闭。

您的测试类和服务类试图分担 IO 服务的责任,但这是行不通的。这里有很多简化,合并类并删除未使用的 future 。

Live On Coliru

诀窍是制作 work对象 optional<> :

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

struct Service {
~Service() {
std::cout << "clean and stop\n";
io_service.post([this]() {
work.reset(); // let io_service run out of work
});

if (worker.joinable())
worker.join();
}

void start() {
assert(!worker.joinable());
worker = std::thread([this] { io_service.run(); std::cout << "exiting thread\n";});
}

private:
boost::asio::io_service io_service;
std::thread worker;
boost::optional<boost::asio::io_service::work> work{io_service};
};

int main() {
{
Service test;
test.start();

std::cin.ignore(1024, '\n');
std::cout << "Start shutdown\n";
}

std::cout << "exiting program\n"; // never printed
}

打印

Start shutdown
clean and stop
exiting thread
exiting program

关于c++ - 从并发析构函数停止 boost::asio::io_service::run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com