使用 ZeroMQ 消息的线程间通信 [英] inter thread comunication using ZeroMQ messages

查看:36
本文介绍了使用 ZeroMQ 消息的线程间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use zeroMQ as a way to implement a messaging system between multiple threads. I tried the code below but it doesn't work; in the specific the call to zmq_recv in each thread doesn't wait/block for any message to be executed.

你能帮我写一段代码吗?

Can you help me with this piece of code?

我使用的是 Linux 操作系统和 gcc

I am using Linux OS and 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;
    }

推荐答案

两个套接字都是 REP.你想要的是 REQ + REP.

Both sockets are REP. What you want is REQ + REP.

这篇关于使用 ZeroMQ 消息的线程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆