我正在使用 boost-asio 使用 C++ 编写多线程服务器。目前我遇到的一个设计问题涉及删除连接。
我有一个服务器实例,它包含一个连接对象 vector 。这些连接接收我解析的命令。一个命令特别处理将数据发送到我的 vector 中的所有连接。
现在,当连接断开时,我正在从 vector 中删除此连接并调用析构函数。当有人“SendAll”同时有人“断开连接”时,我似乎会遇到问题。
谁能推荐一个更好的设计或者给我指明正确的方向?非常感谢任何帮助。谢谢
最佳答案
无论什么类维护这个连接 vector 都需要一个 strand .在 vector 中访问、添加或删除时使用 strand::post
或 strand::dispatch
。 strand concept文档中有详细说明。
A strand is defined as a strictly sequential invocation of event handlers (i.e. no concurrent invocation). Use of strands allows execution of code in a multithreaded program without the need for explicit locking (e.g. using mutexes).
关于C++ 多线程服务器帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640058/