[英]Delegate use of boost asio TCP/IP socket
I created a TCP client that has a boost asio tcp socket and who makes asynchronous read: 我创建了一个具有boost asio tcp套接字的TCP客户端,该客户端进行异步读取:
class TCPClient {
public:
TCPClient(boost::asio::io_service& io_service)
: socket_(io_service) {
// Connect
[...]
// Asynchronous read
socket_.async_read_some(boost::asio::buffer(buffer, buffer.size()),
boost::bind(&TCPClient::handlerRead,
this,
placeholders::error,
placeholders::bytes_transferred));
}
~TCPClient() {}
void handlerRead(const boost::system::error_code& ec, uint32_t bytes) {
if (!ec) {
// process
[...]
socket_.async_read_some(
boost::asio::buffer(buffer, buffer.size()),
boost::bind(&TCPClient::handlerRead,
this,
placeholders::error,
placeholders::bytes_transferred));
}
int getSocketFd() {
return socket_.native_handle();
}
private:
boost::asio::tcp::socket socket_;
};
This is working fine. 一切正常。 But when I am putting this in a thread:
但是当我将其放入线程中时:
boost::asio::io_service io_service;
auto client = new TCPClient(io_service);
std::thread{[&io_service](){ io_service.run(); }};
... and getting file descriptor of the socket: ...并获取套接字的文件描述符:
int socket_fd = client->getSocketFd();
Because I want this part of the program to use the TCP/IP socket to send packets on this socket. 因为我希望程序的这一部分使用TCP / IP套接字在此套接字上发送数据包。 But then, my program is segfaulting with this error:
但是然后,我的程序出现以下错误:
#1 0x000000000041fab0 in boost::asio::detail::task_io_service_operation::complete(boost::asio::detail::task_io_service&, boost::system::error_code const&, unsigned long) ()
#2 0x0000000000420b5f in boost::asio::detail::task_io_service::do_run_one(boost::asio::detail::scoped_lock<boost::asio::detail::posix_mutex>&, boost::asio::detail::task_io_service_thread_info&, boost::system::error_code const&) ()
#3 0x00000000004207df in boost::asio::detail::task_io_service::run(boost::system::error_code&) ()
#4 0x0000000000420eab in boost::asio::io_service::run() ()
Do you have any clue on what is happening here ? 您对这里发生的事情有任何线索吗?
You define io_service
on the stack in one thread. 您可以在一个线程中在堆栈上定义
io_service
。 But you access it from a different thread. 但是您可以从其他线程访问它。 It seems that the object is no longer alive at the moment of
.run()
call. 似乎在
.run()
调用时该对象不再活动。
Moving it to the heap is one possibility. 将其移动到堆是一种可能。 Anyway some deeper analysis of the code, relationship between components and liveness is needed.
无论如何,都需要对代码,组件与活动性之间的关系进行更深入的分析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.