random.cpp
Go to the documentation of this file.
1 /* SPDX-License-Identifier: MPL-2.0 */
2 
3 #include "precompiled.hpp"
4 #include <stdlib.h>
5 
6 #if !defined ZMQ_HAVE_WINDOWS
7 #include <unistd.h>
8 #endif
9 
10 #include "random.hpp"
11 #include "stdint.hpp"
12 #include "clock.hpp"
13 #include "mutex.hpp"
14 #include "macros.hpp"
15 
16 #if defined(ZMQ_USE_LIBSODIUM)
17 #include "sodium.h"
18 #endif
19 
21 {
22 #if defined ZMQ_HAVE_WINDOWS
23  const int pid = static_cast<int> (GetCurrentProcessId ());
24 #else
25  int pid = static_cast<int> (getpid ());
26 #endif
27  srand (static_cast<unsigned int> (clock_t::now_us () + pid));
28 }
29 
31 {
32  // Compensate for the fact that rand() returns signed integer.
33  const uint32_t low = static_cast<uint32_t> (rand ());
34  uint32_t high = static_cast<uint32_t> (rand ());
35  high <<= (sizeof (int) * 8 - 1);
36  return high | low;
37 }
38 
39 static void manage_random (bool init_)
40 {
41 #if defined(ZMQ_USE_LIBSODIUM)
42  if (init_) {
43  // sodium_init() is now documented as thread-safe in recent versions
44  int rc = sodium_init ();
45  zmq_assert (rc != -1);
46 #if defined(ZMQ_LIBSODIUM_RANDOMBYTES_CLOSE)
47  } else {
48  // randombytes_close either a no-op or not threadsafe
49  // doing this without refcounting can cause crashes
50  // if called while a context is active
51  randombytes_close ();
52 #endif
53  }
54 #else
55  LIBZMQ_UNUSED (init_);
56 #endif
57 }
58 
60 {
61  manage_random (true);
62 }
63 
65 {
66  manage_random (false);
67 }
zmq::random_open
void random_open()
Definition: random.cpp:59
precompiled.hpp
zmq_assert
#define zmq_assert(x)
Definition: err.hpp:102
random.hpp
clock.hpp
zmq::random_close
void random_close()
Definition: random.cpp:64
macros.hpp
manage_random
static void manage_random(bool init_)
Definition: random.cpp:39
stdint.hpp
LIBZMQ_UNUSED
#define LIBZMQ_UNUSED(object)
Definition: macros.hpp:6
zmq::generate_random
uint32_t generate_random()
Definition: random.cpp:30
zmq::seed_random
void seed_random()
Definition: random.cpp:20
mutex.hpp


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:58