chenshuo / muduo

Event-driven network library for multi-threaded Linux server in C++11
https://github.com/chenshuo/muduo
Other
14.7k stars 5.15k forks source link

TcpServer 支持异步应答吗? #547

Closed lkkey80 closed 2 years ago

lkkey80 commented 2 years ago

目前看到的例子里面,都是在MessageCallback里直接调用TcpConnectionPtr->send回复消息,是否支持在MessageCallback不回复消息,而是将TcpConnectionPtr传入到另外的自定义线程(第三方线程),然后完成复杂任务后,在自定义线程中调用send应答回复呢?

fortunely commented 2 years ago

TcpConnection的成员函数大部分不是线程安全的,你如果都放到别的线程来执行,必然会涉及到并发访问数据成员的问题。 TcpConnection非线程安全成员函数的调用,只能是在loop所属IO线程。

不过,TcpConnection::send大部分是支持别的线程调用的,你仔细看,里面会调用TcpConnection::sendInLoop,利用sendInLoop来完成排队在所属IO线程执行。

chenshuo commented 2 years ago

TcpConnection::send() 是线程安全的。

现在有一些例子,是在 TcpConnection A 的 message callback 里调用 TcpConnection B 的 send(),比如 examples/socks4a/tcprelay.cc

跨线程的例子可参考 examples/asio/chat/server_threaded_highperformance.cc