-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_thread.cpp
58 lines (48 loc) · 1.36 KB
/
main_thread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <pthread.h>
#include <unistd.h>
#include <cassert>
#include <chrono>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <zmq.hpp>
using namespace std;
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 (true) {
// Wait for next request from client
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 (NULL);
}
int main()
{
using namespace std::chrono_literals;
// Prepare our context and sockets
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");
// Launch pool of worker threads
for (int thread_nbr = 0; thread_nbr != 5; thread_nbr++) {
pthread_t worker;
pthread_create(&worker, NULL, worker_routine, (void*)&context);
}
// Connect work threads to client threads via a queue
zmq::proxy(static_cast<void*>(clients), static_cast<void*>(workers), nullptr);
return 0;
}