2

我正在尝试zeroMQ用作在多个线程之间实现消息传递系统的一种方式。我尝试了下面的代码,但它不起作用;具体来说,每个线程中的调用zmq_recv不会等待/阻止任何消息的执行。

你能帮我处理这段代码吗?

我正在使用 Linux 操作系统和 gcc

此致

AFG

    static void *
    worker_routine (void *context) {
        // Socket to talk to dispatcher
        void *receiver = zmq_socket (context, ZMQ_REP);
        zmq_connect (receiver, "inproc://workers");
        while (1) {

            zmq_msg_t request;
            zmq_msg_init( &request );
            zmq_recv( receiver, &request, 0 );
            printf ("Received request\n");
            // Do some 'work'
            usleep (1000);
            // Send reply back to client
            zmq_send (receiver, &request, 0);
        }
        zmq_close (receiver);
        return NULL;
    }

    int main (void) {

    void *context = zmq_init (1);
    void *clients = zmq_socket (context, ZMQ_REP);
    zmq_bind (clients, "inproc://workers");

    int thread_nbr;
    for (thread_nbr = 0; thread_nbr < 5; thread_nbr++) {
        pthread_t worker;
        pthread_create (&worker, NULL, worker_routine, context);
    }

    zmq_close (clients);
    zmq_term (context);
    return 0;
    }
4

3 回答 3

6

两个插座都是 REP。你想要的是 REQ + REP。

于 2011-04-01T17:27:53.177 回答
3

创建线程后,您将立即关闭套接字和 ZeroMQ。他们可能没有时间达到阻塞状态,如果他们这样做了,一旦你破坏 zmq 上下文,他们就会失败。从zmq_term 手册页

上下文终止按以下步骤执行:

当前在上下文中打开的套接字上正在进行的任何阻塞操作都应立即返回ETERM 错误代码。

于 2011-03-29T18:29:51.317 回答
0

首先,正如@sustrik 所说,您需要使用REQand REP,主线程和工作线程都不能是REP.

其次,您需要在主线程中提供某种阻塞循环:

int main (int argc, char **argv)
{
    void *context = zmq_init (1);
    void *clients = zmq_socket (context, ZMQ_REP); // use ZMQ_REQ on the clients
    zmq_bind (clients, "inproc://workers");

    int thread_nbr;
    for (thread_nbr = 0; thread_nbr < 5; thread_nbr++) {
        pthread_t worker;
        pthread_create (&worker, NULL, worker_routine, context);
    }

    while (TRUE)
    {
        // worker thread connected asking for work
        zmq_msg_t request;
        zmq_msg_init (&request);
        zmq_recv (clients, &amp;request, 0);
        zmq_msg_close (&request);

        // do whatever you need to do with the clients' request here

        // send work to clients
        zmq_msg_t reply;
        zmq_msg_init_data (&reply, "Reply", 5, NULL, NULL);
        zmq_send (clients, &amp;reply, 0);
        zmq_msg_close (&reply);
    }

    zmq_close (clients);
    zmq_term (context);
    return 0;
}
于 2011-04-06T15:08:18.413 回答