gpt4 book ai didi

c++ - io_service 在线程内运行

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

为什么在这个简单的类中,如果我直接使用 io.run() 函数将被调用,否则如果要求运行到其他线程,打印将不会被调用?

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

using namespace std;

class test
{
public:
test()
{
io.post(boost::bind(&test::print, this));
//io.run();
t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
}

void print()
{
cout << "test..." << endl;
}

private:
boost::thread t;
boost::asio::io_service io;
};

int main()
{
test();
return 0;
}

最佳答案

线程对象在允许 io_service 完全运行之前被销毁。 thread 析构函数 documentation状态:

[...] the programmer must ensure that the destructor is never executed while the thread is still joinable.

如果定义了 BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE,程序将中止,因为线程析构函数将调用 std::terminate()


如果 io_service 应该运行完成,则考虑在 Test 的析构函数中加入线程。这是一个完整的例子 demonstrates在线程完成时同步:

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

class test
{
public:
test()
{
io.post(boost::bind(&test::print, this));
t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
}

~test()
{
if (t.joinable())
t.join();
}

void print()
{
std::cout << "test..." << std::endl;
}

private:
boost::thread t;
boost::asio::io_service io;
};

int main()
{
test();
return 0;
}

输出:

test...

关于c++ - io_service 在线程内运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26510075/

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