1

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.

GuLearn
  • 1,814
  • 2
  • 18
  • 32
  • I have a similar problem. I plan to use thread local storage to manage a socket. But I have no idea if it will work. – tdelaney Aug 09 '13 at 04:25

1 Answers1

1

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.

Community
  • 1
  • 1
raffian
  • 31,267
  • 26
  • 103
  • 174
  • Thank you for mentioning the `tss.hpp`. It sounds promising, I'll try to fit it in my program. +1 – GuLearn Aug 09 '13 at 13:15
  • Here's a [post](http://stackoverflow.com/a/6021676/642070) on how to dynamically init thread local storage in boost. – tdelaney Aug 09 '13 at 16:22
  • @tdelaney Thanks for providing the link. The `thread_local` keyword in C++11 also works – GuLearn Aug 09 '13 at 16:25