防止ZMQ c++调用rand()

Prevent ZMQ c++ from calling rand()

本文关键字:rand 调用 ZMQ c++ 防止      更新时间:2023-10-16

我在Ubuntu 10.04.5 LTS上使用ZMQ 4.1.2。

我有一个c++程序,它用一个固定的数字播种rand(),然后调用rand() ~100k次并存在。我发现当我两次重新运行同一个程序时,我得到的是不同的随机数。

如果我有一个ZMQ套接字打开之前,我开始我的100k绘制,似乎ZMQ库本身调用rand()和搞乱我的可重复性。

this->context = new zmq::context_t(1);
this->socket = new zmq::socket_t(*this->context, ZMQ_PUB);
socket->connect("tcp://localhost:5556"); // offending line

我所需要做的就是省略调用socket->connect(),并且我对rand()的调用行为是确定性的。

这是ZMQ中的一个bug(特性)吗?或者这也发生在底层TCP套接字上?

您希望使用rand_r而不是rand,以便您的使用不会与使用rand的其他库冲突。例如

unsigned int seed = YOUR_INITIAL_SEED;
for (int x = 0; x < 100000; x++)
{
    unsigned int r = rand_r(&seed);
    DoMyThing(r);
}
https://linux.die.net/man/3/rand