[Libwebsockets] 回复: libwebsocket thread safe?

Jeffrey Zhao chunyong.zhao at qq.com
Mon Apr 13 10:27:40 CEST 2015


Dear Andy
Thanks for the reply.
But when I am testing, call libwebsocket_callback_on_writable() from another thread, the call almost has no effect, only little chance to be effective. It seems I must call libwebsocket_callback_on_writable() from libwebsockets thread itself, which is always effective.


Do you know the reasons?




>> 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.

------------------ 原始邮件 ------------------
发件人: "Andy Green";<andy at warmcat.com>;
发送时间: 2015年4月10日(星期五) 上午7:07
收件人: "Jeffrey Zhao"<9538358 at qq.com>; "libwebsockets at ml.libwebsockets."<libwebsockets at ml.libwebsockets.org>; 

主题: Re: libwebsocket thread safe?





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.

-Andy

>> thank you very much!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://libwebsockets.org/pipermail/libwebsockets/attachments/20150413/f2c8b15a/attachment.html>


More information about the Libwebsockets mailing list