I'd like to pass a string argument to a child thread ( that is continuously reading a socket ) and call a setsockopt()
with that argument on that socket.
I'm using ZeroMQ sockets, so calling setsockopt()
is not threadsafe here, I'd call the setsockopt()
from the child thread ( as was recommended here ). An argument update would occur probably only once in billions of read cycles, and it feels a bit wrong to add an if
-structure to the child's every cycle like this:
bool new_arg_available;
std::string new_arg;
while(1){
sub_socket->recv(data); // . . . . . . a blocking method call
printData(data)
... // . . . . . . data can set new_arg_available
if (new_arg_available){ // . . . . . . synchronization goes here
sub_socket->setsockopt(ZMQ_SUBSCRIBE, new_arg, ... );
new_arg_available = false;
}
}
For me, the most straightforward would probably be either:
Add a mutex to the global namespace, lock it when a
new_arg
available in the parent thread, and unlock it from the child thread.use a
std::atomic<bool>
and use it the same way as in 1.
However, what I would like to achieve somehow is to make the child interruptible, so that I could eliminate the if
-structure from the end of the while(){...}
block. I wouldn't mind the penalty of a context switch, because this event would be so seldom.
I'm relatively new to C++, and I would like to learn about best practices here, how to achieve this in an efficient way. I would like to solve it without using Boost, the only examples I could find to achieve interruptible threads were using Boost.