C++ Multithreaded server help

拥有回忆 提交于 2019-12-09 19:17:51

问题


I'm working on a multithreaded server in c++ using boost-asio. Currently a design problem I'm running into deals with erasing a connection.

I have a single server instance which holds a vector of connection objects. These connections receive commands which I parse. One command in particular deals with sending data to ALL connections in my vector.

Now when a connection disconnects I'm currently erasing this connection from the vector and calling the destructor. It seems like I'm going to run into problems when someone 'SendAll' at the same time someone 'Disconnect'.

Could anyone recommend a better design or just point me in the right direction? Any help greatly appreciated. Thanks


回答1:


Whatever class maintains this vector of connections needs a strand. Use strand::post or strand::dispatch when accessing, adding to, or removing from the vector. The strand concept is explained in detail in the documentation.

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).




回答2:


Is putting a lock around the vector not an option? Have every access to the vector first acquire a lock; that will prevent your race condition. As long as server connections don't come and go very frequently, it won't be a bottleneck.



来源:https://stackoverflow.com/questions/4640058/c-multithreaded-server-help

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!