[zeromq-dev] Threading questions

Martin Sustrik sustrik at 250bpm.com
Fri Feb 19 08:58:19 CET 2010


gonzalo diethelm wrote:

> The documentation for zmq_init() says this about the two initial parameters:
> 
>    1. app_threads specifies maximal number of application threads that
>       can own open sockets at the same time. At least one application
>       thread should be defined.
>    2. io_threads specifies the size of thread pool to handle I/O
>       operations. The value shouldn’t be negative. Zero can be used in
>       case only in-process messaging is going to be used, i.e. there
>       will be no I/O traffic.
> 
> Can anybody provide more information about what exactly one is 
> controlling with app_threads? What happens if I specify 2 but use a 
> socket on only one of them?

0MQ has to allocate some infrastructure for each thread you'll be 
calling it from. So just enter number of threads in your application 
accessing 0MQ and that will do. You can sure specify more application 
threads - 0MQ will just allocate more infrastructure than actually needed.

> Say I want to have threading operations on three separate threads. Do I 
> have to call zmq_init() just once, with app_threads = 3, before I spawn 
> the threads? Or do I have to call zmq_init() once on each thread, each 
> time with app_threads = 3?

Call it once in the main thread. Use the resulting context to create 
sockets in each of your threads.

> Can I have more than one thread calling zmq_recv() on different sockets 
> at the same time?

No. Each socket object can be created and used from at most one thread. 
For communication between threads use inproc transport (zmq_inproc(7))

See an example here:

http://www.zeromq.org/area:docs-v20#toc15

> I want to have a program that receives a constant stream of business 
> messages and, every once in a while, a couple of “administrative” 
> messages (enquiring state, asking it to pause or shut down, etc.). I 
> think I have at least two ways of doing this:
>  
>    1. One socket, one thread receiving messages, it decides what kind of
>       message it is (business or administrative) and processes it.
>    2. Two sockets, two threads. On one thread I only receive business
>       messages on the business socket; on the other thread I only
>       receive administrative messages on the administrative socket.
> Is there any advantage you can see on one method over the other? Model 2 
> seems to provide a better abstraction.

As far as I understand your business messages are a stream (either 
pub/sub or upstream/downstream) while your administration commands are 
req/rep. You'll need 2 sockets for that.

> Are all of the threading rules the same when using 0mq on C / C++ and 
> when using it on Java?

Yes. It's the same. Java binding is just a thin wrapper over underlying 
C library.

HTH
Martin



More information about the zeromq-dev mailing list