GuLearn
GuLearn

Reputation: 1864

Using zmq socket in a callback function

I have a callback function which will be called in a thread that I don't have any access or control to (a library created that thread, and requires me to exposure the callback function to that thread). Since a zmq socket is not thread safe, here is what I'm doing:

void callback () {
    zmq::socket_t tmp_sock(...); // create a socket which will be used only once
    ...
}

However, the callback is being invoked very frequently (hundreds of times per sec). Is there a better solution to use the socket more efficiently? I asked this because The Guide says: If you are opening and closing a lot of sockets, that's probably a sign that you need to redesign your application.

Edit: Based on @raffian's answer. A thread_local static (available in C++11) variable in the callback function works fine.

Upvotes: 1

Views: 1028

Answers (1)

raffian
raffian

Reputation: 32056

I asked the same question, but in Java:

The principals are the same: pre-initialize a pool of worker threads, each with a dedicated socket, ready to use for reading/writing. In the Java example, I use ThreadLocal; I suppose in C++ you can use #include <boost/thread/tss.hpp>. This approach is consistent with ZeroMq's guide; use sockets only in the threads that created them.

I'm not a C++ programmer, but if you use this approach, you'll have to do something like this:

void callback () {
    workerPool.doTask( new Task(args here));
    ...
}

Create a Task, with arguments, and send it to the workerPool, where it's assigned to a thread with dedicated socket. You'll want to create the worker pool with enough threads to accommodate load, nevertheless, concurrency shouldn't be a concern.

Upvotes: 1

Related Questions