wslay icon indicating copy to clipboard operation
wslay copied to clipboard

not work with thread

Open yjp211 opened this issue 10 years ago • 4 comments

I use wslay with thread pool in c, and I got a problem。 To simplify the problem, as the fork-echoserv example:

struct wslay_event_msg *g_msg = NULL;

void echo_data (wslay_event_context_ptr ctx){
    printf("--->echo data!!!\n");
    wslay_event_queue_msg(ctx, g_msg);
}

void on_msg_recv_callback(wslay_event_context_ptr ctx,
                          const struct wslay_event_on_msg_recv_arg *arg,
                          void *user_data)
{
  /* Echo back non-control message */
  if(!wslay_is_ctrl_frame(arg->opcode)) {
      struct wslay_event_msg *msgarg = malloc(sizeof(struct wslay_event_msg));
      msgarg->opcode = arg->opcode;
      msgarg->msg = arg->msg;
      msgarg->msg_length = arg->msg_length;

       g_msg = msgarg;

       //this is work !!
       //echo_data(ctx); 

       //but this not
       pthread_t thread;
       pthread_create(&thread, NULL, (void *)echo_data, (void *)ctx);
  }
}

use thread, package can't be send.

。。。。。。 I just find this problem only in OSX, it's work in Linux

yjp211 avatar Jul 09 '15 09:07 yjp211

I think working well in linux is just coincidence. wslay has no mutex inside it, and using wslay_event_context_ptr from multiple threads is unsafe, and must be avoided. If some work must be done in the different thread, all required data must be copied, and get passed to the new thread. Just copying pointer value is not enough. You have to make new buffer of size arg->msg_length, and copy the data pointed by arg->msg of length arg->msg_length to the new buffer, and pass it to the thread.

tatsuhiro-t avatar Jul 09 '15 12:07 tatsuhiro-t

This example is just trying to show that the asynchronous call to write in recv_callback does not send a packet at OSX.

Such copy data and the use of global variables in this example, just lazy : )

yjp211 avatar Jul 10 '15 01:07 yjp211

hello , I meed the same problem, I want to send lots of data, but wslay_event_queue_msg seems to work only in main thread. Is there any idea?

xsjqqq123 avatar Nov 23 '16 14:11 xsjqqq123

wslay_event_context must not be used by multiple thread at the same time. If you'd like to use it from multiple thread, use mutex around the calls.

tatsuhiro-t avatar Nov 23 '16 15:11 tatsuhiro-t