Belle II Software  release-08-01-10
ZMQParent.cc
1 /**************************************************************************
2  * basf2 (Belle II Analysis Software Framework) *
3  * Author: The Belle II Collaboration *
4  * *
5  * See git log for contributors and copyright holders. *
6  * This file is licensed under LGPL-3.0, see LICENSE.md. *
7  **************************************************************************/
8 #include <framework/pcore/zmq/utils/ZMQParent.h>
9 #include <bitset>
10 
11 using namespace std;
12 using namespace Belle2;
13 
14 ZMQParent::~ZMQParent()
15 {
16  terminate();
17 }
18 
19 void ZMQParent::terminate()
20 {
21  if (m_context) {
22  m_context->close();
23  m_context.reset();
24  }
25 }
26 
27 void ZMQParent::reset()
28 {
29  m_context.release();
30 }
31 
32 std::string ZMQParent::createIdentity(unsigned int pid)
33 {
34  char hostname[HOST_NAME_MAX];
35  gethostname(hostname, HOST_NAME_MAX);
36 
37  if (pid == 0) {
38  pid = getpid();
39  }
40 
41  return std::string(hostname) + "_" + std::to_string(pid);
42 }
43 
44 void ZMQParent::initialize()
45 {
46  if (m_context) {
47  return;
48  }
49  m_context = std::make_unique<zmq::context_t>(1);
50 }
51 
52 #if defined(__GNUC__) && !defined(__clang__)
53 #pragma GCC diagnostic push
54 #pragma GCC diagnostic ignored "-Wstack-usage="
55 #endif
56 unsigned int ZMQParent::poll(const std::vector<zmq::socket_t*>& socketList, int timeout)
57 {
58  B2ASSERT("Only allow to poll on maximal 8 sockets at the same time!", socketList.size() <= 8);
59  std::bitset<8> return_bitmask;
60  zmq::pollitem_t items[socketList.size()];
61 
62  for (unsigned int i = 0; i < socketList.size(); i++) {
63  items[i].socket = static_cast<void*>(*socketList[i]);
64  items[i].events = ZMQ_POLLIN;
65  items[i].revents = 0;
66  }
67 
68  try {
69  zmq::poll(items, socketList.size(), timeout);
70 
71  for (unsigned int i = 0; i < socketList.size(); i++) {
72  return_bitmask[i] = static_cast<bool>(items[i].revents & ZMQ_POLLIN);
73  }
74  return return_bitmask.to_ulong();
75  } catch (zmq::error_t& error) {
76  if (error.num() == EINTR) {
77  return 0;
78  } else {
79  // cannot handle, rethrow exception
80  throw;
81  }
82  }
83 }
84 #if defined(__GNUC__) && !defined(__clang__)
85 #pragma GCC diagnostic pop
86 #endif
Abstract base class for different kinds of events.