我想了解如何有效地使用ZMQ多线程(所以发送不阻止接收和阻止发送)。是否有可能以某种方式在ZMQ中同时使用Send/Recv(通过多线程)?
我想使用ZMQ_DONTWAIT
标志,但是在发送数据时,它有时不会被发送(EAGAIN
错误,所以我将不得不重新排队消息,这在处理兆字节数据时浪费资源)。
我没有想出下面的代码:
Concurrency::concurrent_queue<zmq::message_t> QUEUE_IN;
Concurrency::concurrent_queue<zmq::message_t> QUEUE_OUT;
void SendThread(zmq::context_t &context) {
zmq::socket_t zmq_socket(context, ZMQ_DEALER);
zmq_socket.connect(string_format("tcp://%s:%s", address, port).c_str());
zmq::message_t reply;
while (true) {
while (QUEUE_OUT.try_pop(reply))
zmq_socket.send(reply);
Sleep(1);
}
}
void RecvThread(zmq::context_t &context) {
zmq::socket_t zmq_socket(context, ZMQ_DEALER);
zmq_socket.connect(string_format("tcp://%s:%s", address, port).c_str());
zmq::message_t reply;
while (true) {
while (zmq_socket.recv(&reply))
QUEUE_IN.push(reply);
}
}
void ConnectionThread()
{
zmq::context_t context(1);
std::thread* threads[2] = {
new std::thread(SendThread, context),
new std::thread(RecvThread, context)
};
threads[0]->join();
}
然而这将需要在服务器端有两个插座,我会需要确定,而我需要发送的数据和我需要在服务器端收听,对吧? 有没有办法使用一个套接字,但在多线程环境中使用发送和接收?
我可能会喜欢在一个套接字上使用asychroniously,但是在研究异步样本之后,我仍然没有把握这个想法,因为没有太多的评论。
您不需要多个上下文,只需要多个线程。 – 2014-10-17 16:15:04
@JohnJefferies你是对的,我误解了警告[在这里指南](http://zguide.zeromq.org/page:all#Getting-the-Context-Right),单独的过程需要一个单独的上下文,单独线程不。我相应地更新了我的答案。 – Jason 2014-10-17 17:58:46