码迷,mamicode.com
首页 > 编程语言 > 详细

zeromq学习记录(五)vc下多线程

时间:2016-04-02 14:44:19      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:

本节演示使用多线程的代码

由于示例中使用的是pthead函数 为了在windows下运行 我做了点改动

使用c++11 的thread函数

代码如下 与第一节的hwclient 配套使用

技术分享
// mttest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "zhelpers.hpp"
#include <thread>

void worker_routine(void* arg)
{
    zmq::context_t *context = (zmq::context_t *) arg;

    zmq::socket_t socket(*context, ZMQ_REP);
    socket.connect("inproc://workers");

    while (1)
    {
        zmq::message_t request;
        socket.recv(&request);
        std::cout << "Received request: [" << (char*)request.data() << "]" << std::endl;

        //  Do some ‘work‘
        Sleep(1);

        //  Send reply back to client
        zmq::message_t reply(6);
        memcpy((void *)reply.data(), "World", 6);
        socket.send(reply);
    }
    return;
}

int main()
{
    zmq::context_t context(1);
    zmq::socket_t clients(context, ZMQ_ROUTER);
    clients.bind("tcp://*:5555");
    zmq::socket_t workers(context, ZMQ_DEALER);
    workers.bind("inproc://workers");

    std::thread t[5];
    for (int thread_nbr = 0; thread_nbr < 1; thread_nbr++)
    {
        t[thread_nbr] = std::thread(worker_routine, (void *)&context);
    }

    zmq::proxy(clients, workers, NULL);

    for (int thread_nbr = 0; thread_nbr < 1; thread_nbr++)
    {
        t[thread_nbr].join();
    }

    return 0;
}
View Code

 

 

技术分享

技术分享
// temp.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "zhelpers.hpp"
#include <thread>
void step1(void *arg) {

    zmq::context_t * context = static_cast<zmq::context_t*>(arg);

    //  Signal downstream to step 2
    zmq::socket_t sender(*context, ZMQ_PAIR);
    sender.connect("inproc://step2");

    s_send(sender, "");

    return;
}

//  Step 2 relays the signal to step 3

void step2(void *arg) {

    zmq::context_t * context = static_cast<zmq::context_t*>(arg);

    //  Bind to inproc: endpoint, then start upstream thread
    zmq::socket_t receiver(*context, ZMQ_PAIR);
    receiver.bind("inproc://step2");

    std::thread t = std::thread(step1, context);

    //  Wait for signal
    s_recv(receiver);

    //  Signal downstream to step 3
    zmq::socket_t sender(*context, ZMQ_PAIR);
    sender.connect("inproc://step3");
    s_send(sender, "");

    t.join();
    return;
}


int main()
{
    zmq::context_t context(1);

    //  Bind to inproc: endpoint, then start upstream thread
    zmq::socket_t receiver(context, ZMQ_PAIR);
    receiver.bind("inproc://step3");

    std::thread t = std::thread(step2, &context);

    //  Wait for signal
    s_recv(receiver);

    std::cout << "Test successful!" << std::endl;

    t.join();
    return 0;
}
View Code

 

zeromq学习记录(五)vc下多线程

标签:

原文地址:http://www.cnblogs.com/itdef/p/5347478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!