using libev with multiple threads

钱晓明 mailtoantares at
Sat Feb 2 00:39:50 CET 2013

I am happy to see this e-mail because I can contribute some thing :-)...
This is exactly the same need for me and I write some code to do this. They are in attachment files.
The key to accomplish this goal is:
1. create new event loop for per worker thread, with a pipe and a extra ev_io to watch pipe's read event. This is done before the worker thread start, so the main thread(listen thread) can hold these in a struct in a list. It is important to know that pipe's read event is watched in the worker thread's event loop, not the main event loop.
2. once new connection accepted, the listen thread send the accepted socket fd on pipe, just using round robin to determine which thread struct(this contain the pipe) to use
3. the worker thread use a particular callback for the pipe read watcher. In this callback(dispatched_socket_arrived in example), create normal read/write watchers for socket fd just received on pipe. Just start the read watcher, not start the write watcher for this socket fd
4. so data send/received on this socket fd is processed on worker thread.
I hope this can help you.

在2013年01月31 22时31分,"Chris Herssens"<chris.herssens at> 写道:

I want to use libev with multiple threads for the handling of tcp connections. What I want to is:

The main thread listen on incoming connections, accept the connections and forward the connection to a workerthread.

I have a pool of workerthreads. The number of threads depends on the number of cpu's. Each worker-thread has an event loop. The worker-thread listen if I can write on the tcp socket or if somethings available for reading.

I looked into the documentation of libev and I known this can be done with libev, but I can't find any example how I have to do that.
Does someone has an example? 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() ?

Since I new in using libev I really need an example how to dispatch an incoming tcp connection to a worker-thread. I have started to implement it, 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.  Also Is there a way to block the ev_loop if there no active watchers ?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: socket_server.cpp
URL: <>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: socket_server.h
Type: application/octet-stream
Size: 3392 bytes
Desc: not available
URL: <>

More information about the libev mailing list