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