0

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?

Community
  • 1
  • 1

1 Answers1

1

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.

fredrik
  • 6,483
  • 3
  • 35
  • 45
  • I don't think such a thing exists - you simply have to add locks around each access. – fredrik Mar 10 '13 at 06:55
  • I think that there are try_lock in the mutex class. But then you wouldn't get the nice automatic scope lock. – fredrik Mar 10 '13 at 06:57
  • [Here](http://www.boost.org/doc/libs/1_42_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_concepts.lockable.try_lock) you have the try_lock function. You need to manually make sure that you either get the lock, or return from the function without accessing the map if you choose to use this method. But it should work equally well. – fredrik Mar 10 '13 at 07:00
  • As an aside, websocket++ is amazing! I can't wait for 1.0 –  Mar 10 '13 at 07:16