[Libwebsockets] Quick API question

Andy Green andy at warmcat.com
Mon Mar 23 22:00:31 CET 2020



On Mon, Mar 23, 2020 at 15:54, Brice Hamon <normandviking at gmail.com>
wrote:
 > Hi guys,
 >
 > I have a quick question on lws usage.
 >
 > Server side of the API, when I get notified of a client's connection
 > on LWS_CALLBACK_ESTABLISHED, the struct per_session_data is allocated
 > by the library, and deleted on close. I call that pointer pss.
 >
 > I've been using that address to reference the client's connection on
 > other threads as this server is totally MT but one thread
 > encapsulates the lws safely. I am also using lws with external event
 > loop support, which works beautifully.
 >
 > Of course as things happen, the client connection may be closed,
 > therefore the pss invalidated, while I have in flight messages in
 > queues.

Right... it isn't directly safe to store and pass around the wsi or pss
to other threads... the lws service loop feels that it owns the memory
both of those point to, and it can and will free / invalidate them --
synchronously and safely from the perspective of the service thread,
but asynchronously and randomly from the perspective of any other
thread.

 >
 > So far I have a fast hash to keep track of the validity of a pss, in
 > the thread managing lws. So far so good.
 >
 > Now my question is: is there a way to ask lws if that pss is still
 > active (referenced? ), instead of me doing it externally?

The main point is that lws does not in fact invalidate these objects
randomly, if you got an ESTABLISHED type callback, you can bank on
getting a CLOSED type callback in the lws thread context before
anything is freed.  So there's some basic order to the process you
should be able to leverage to enforce sanity on what you're doing.

Eg, in ESTABLISHED and CLOSE, add and remove entries on a mutex-locked
list of valid wsi / pss, using locking that any other thread that will
see them respects when derefencing the copied pointer.   Now while
another thread wants to reference a pss it was told about, it can lock
the "valid pss" list, check its pss is in there, do its stuff, and
unlock the list.  In the case lws gets the idea to CLOSE, it will stall
trying to get the lock for the "valid pss" list to remove the pss
that's CLOSE-ing and so defer the free() until definitely no other
thread is using the pss.  You don't want the other threads to hold the
lock long, but usually its possible to prepare big things first and
then lock the pss and just point to what you prepared, and release the
lock immediately.

 >
 > I am still using the 3.0 Stable, soon to upgrade to 4.0 stable on
 > OpenSuse 15.1.

Managing the validity list using your own locking should work on any
recent version.

-Andy


More information about the Libwebsockets mailing list