using libev with multiple threads

Marc Lehmann schmorp at
Thu Jan 31 17:44:37 CET 2013

On Thu, Jan 31, 2013 at 03:31:01PM +0100, Chris Herssens <chris.herssens at> wrote:
> Does someone has an example?

Hopefully somebody has :)

> I think that I have to use the ev_loop_new() api, for the worker-threads
> and for the main thread I have to use the ev_default_loop() ?

No - you can do this, but you can also forget the main thread vs. others
distinction and use ev_loop_new in every thread, if that simplifies your

> but I don't get it work. In the main thread I start the default loop. And
> if I received new connection I create a watcher and use the ev_io_start
> with the loop that I create in the workerthread. It seems that the callback
> function of the watcher is not always triggered.

Yes, because using the same loop from different threads causes problems like
these at best and corruption at worst.

What you would need to do is queue the new conenction somehow and then use
ev_async_send to signal an ev_async watcher of some worker thread.

There are other possible algorithms - you could use accept() in all your
worker threads for example (which might or might not cause fighting between
them, depending on how busy your workers are).

You could also do something like round-robin by accept'ing conenctions in
one thread, then stop the accept watcher and signal the next worker thread
to accept some connections and so on. That might or might not be better
than having a central dispatcher.

> Also Is there a way to block the ev_loop if there no active watchers ?

I am not sure what you mean - if you don't want ev_run to return even
when no watchers are active, then you can use ev_ref, or a dummy
watcher. However, with no active watchers your thread will block forever,
so that isn't really useful.

                The choice of a       Deliantra, the free code+content MORPG
      -----==-     _GNU_    
      ----==-- _       generation
      ---==---(_)__  __ ____  __      Marc Lehmann
      --==---/ / _ \/ // /\ \/ /      schmorp at
      -=====/_/_//_/\_,_/ /_/\_\

More information about the libev mailing list