本节演示使用多线程的代码
由于示例中使用的是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; }
// 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; }
时间: 2024-10-08 09:47:49