Dcow
Dcow

Reputation: 1463

Calling socket->native_handle() from another thread

I'm writing some asio/tcp server and would like to map native socket descriptor with tcp session identifier. I'm writing id getter like:

inline int get_session_id() { return socket_.native_handle(); }

And calling from second (packets dispatching thread) thread like:

cout << session_shared_ptr->get_session_id() << endl;

and it writes valid id only for first time, so I guess to something in my implementation is bad.

Can anyone advice me where I did mistake?

Upvotes: 1

Views: 794

Answers (1)

sehe
sehe

Reputation: 393674

Firstly, using the native handle as a session id strikes me as a fantasticically bad idea.

Not only did you pick an implementation defined backdoor, but also you picked one that is not portable - so your code risks getting different semantics across platforms.

Remember, these are the underlying handles of an abstraction. The abstractions exist for a reason! Who knows, if your network gets reconnected the native handle may change. Nowhere is it documented that you can retain the handle and rely on it to identify the API object.


Of course when you do multi threading, you have to keep in mind everything you always do when threading:

  • synchronize access to shared state and resources
  • coordinate the lifetime of such objects
  • guard against starvation and dead/soft locks while doing the above

Now, you don't speak about synchronization measures, so you have a data race:

Thread Safety

Distinct objects: Safe.
Shared objects: Unsafe.

The standard specifies a data race as Undefined Behaviour; Anything can happen. You can be thankful your house didn't burn down. Yet.


All in all: just use a dependable ID. Generate a UUID and store it in the session. Use the C++ object identity (i.e. address) for identification if you know you don't move sessions with equality.

If you must for some useful reason access the socket from another thread, provide synchronization (mutex - mutual exclusion, or by way of posting to the session strand).

Upvotes: 3

Related Questions