This example for websocket++ is exactly what I want to do at its' core.

While the users can easily be tracked with websocketpp::connection_hdl, I need to keep more information on them much like how stack probably keeps track of which page we're looking at to update votes, comments, answers, messages in the upper left corner, etc.

I just found out that the std::queue is not perfectly thread-safe does .push() fail or wait while locked in this code example? and am going to find a way (probably with a stack q) to work in boost::lockfree::queue Thread-Safe C/C++ queue optimized for push. More importantly, I just found out that thread-safe vectors are much more trouble Threadsafe Vector class for C++

From the code in the first link, how can I track user data (such as the currently viewed stack question) thread-safely without locking & blocking?

有帮助吗?

解决方案

I'm actually doing this myself in a websocket++ application, although I don't use the experimental branch.

What I do is that I create a UserData object (which I have defined) in the on_open, which takes the connection in the constructor. Then I place that object on the a std::map<std::string, connection_hdl>. The string is the serialized connection, which gives a way to uniquely identify it. You could experiment with std::map<connection_hdl, UserData>.

When I want to find the UserData i simply look up the connection in the map and it returns the UserData.

Then to get it thread-safe you need to do a boost::unique_lock<boost::mutex> every time you access the std::map. Almost no std classes are thead-aware, so you should always add guards like this.

Edit: Here is the example in the stable websocket++ which shows one way of how to do this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top