[Libwebsockets] libwebsocket thread safe?

Andy Green andy at warmcat.com
Fri Apr 10 01:07:41 CEST 2015

On 9 April 2015 23:58:36 GMT+08:00, Jeffrey Zhao <9538358 at qq.com> wrote:
>> Dear sir
>> If I use one dedicated ws thread to create libwebsocket  context and
>run libwebsocket_service() loop with maximum timeout value.
>> In this case,
>> 1. Will there be new thread(s) created within libwebsocket itself?

No.  It is completely singlethreaded.

>> 2. Is all callback functions(maybe triggered by different wsi) are
>processed in sequence, not in parrarell?

Yeah.  It is singlethreaded.

If you need it to scale for server case, you may run multiple threads or processes, one per cpu core.  This scales very very well.

>> 3. To write data to ws client, is it safe to let another thread to
>call libwebsocket_callback_on_writable() to the same context created by
>the dedicated ws thread? Will there be any problem?

That - alone - should be safe from other thread contexts.  But you must also watch for the logical wsi lifecycle ending asynchronously (the service thread closes and deletes the wsi, and then your other thread tries to use it) and cancel any use of the dead wsi from another thread.  You can know the wsi is going to get deleted by handling the CLOSE callback.


>> thank you very much!

More information about the Libwebsockets mailing list