boost-asio在两个线程c++之间进行通信
boost asio communicate between two threads c++
我正在使用boost asio创建客户端和服务器应用程序。情况是,我创建了一个用于实例化服务器对象的线程,而主线程将实例化客户端对象。这些对象中的每一个都有自己的io_service,它们在两个线程中独立运行。我现在需要的是,在不使用客户端和服务器之间的套接字的情况下,将一些信息从服务器对象传递回主线程。我需要传递的信息是服务器使用端口(0)获取的端口和服务器从客户端接收的请求。
有很多太少的代码,但这里是:
#include <boost/asio.hpp>
#include <boost/optional.hpp>
#include <boost/thread.hpp>
#include <iostream>
using namespace boost::asio;
struct asio_object {
protected:
mutable io_service io_service_;
private:
boost::optional<io_service::work> work_ { io_service::work(io_service_) };
boost::thread th { [&]{ io_service_.run(); } };
protected:
asio_object() = default;
~asio_object() { work_.reset(); th.join(); }
};
struct Client : asio_object {
public:
void set_message(std::string data) {
io_service_.post([=]{
message = data;
std::cout << "Debug: message has been set to '" << message << "'n";
});
}
private:
std::string message;
};
struct Server : asio_object {
Client& client_;
Server(Client& client) : client_(client) {}
void tell_client(std::string message) const {
client_.set_message(message);
}
};
int main()
{
Client client;
Server server(client);
server.tell_client("Hello world");
}
(这是一个有点疯狂的猜测,因为你没有准确地描述你的问题)
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 构造函数和转换运算符之间的重载解析
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数