C++ Multithreaded server help

2019-04-11 06:57发布

问题:

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.