Saturday 15 May 2010

c++ - Is is possible to somehow use Send/Recv in ZMQ simultaniousely(by multithreading)? -



c++ - Is is possible to somehow use Send/Recv in ZMQ simultaniousely(by multithreading)? -

i trying come how utilize zmq multithread (so send doesn't block receive , receive doesn't block send).

i wanted utilize zmq_dontwait flag when sending data, not send (eagain error, have re-queue message waste of resources when dealing megabytes of data).

i did come next code:

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(); }

however require 2 sockets on server end, , need identify need send info , need hear on server end, right? there no way utilize 1 socket yet utilize send , receive in multithreaded environment?

i maybe asychroniously on 1 socket, after studying async sample still don't grasp thought there aren't much comments around it.

avoiding sleep

to avoid sleep, can utilize zmq_poll() using zmq_pollout event protect send(). don't need utilize zmq_dontwait. [i used c function there, binding have equivalent.]

routing recvthread

one cannot share sockets between threads, 2 sockets needed work. server need 1 socket (presumably router) bound 2 ports. when receives message, need know send reply...

when router socket receives message, zmq internals adds frame message identity of sender. frame seen server code, utilize same identity frame when constructing message reply sender. in case, that's client's sendthread. otoh, want reply client's receive socket, identity frame must that.

the thing left how server obtains identity frame of client's receive socket. that, you'll need invent little protocol. arranging client's recvthread send 1 message server enough. server should understand message , retain identity frame of client's receive socket, , utilize re-create of when constructing reply messages.

all of explained in guide under "exploring router sockets".

c++ multithreading sockets zeromq

No comments:

Post a Comment