防止 ZMQ c++ 调用 rand()

Prevent ZMQ c++ from calling rand()

我在 Ubuntu 10.04.5 LTS 上使用 ZMQ 4.1.2。

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

如果我在开始 100k 绘制之前打开了 ZMQ 套接字,则 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 中的错误(功能)吗?或者底层的 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