Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ helpers: s_set_id generates the same id if called on the same host #572

Open
luca-drf opened this issue Jul 30, 2015 · 1 comment
Open

Comments

@luca-drf
Copy link

In the definition of s_set_id (zmq::socket_t &) in zhelpers.hpp the random function (in within macro) is not seeded, hence, if called from the same host generates always the same id.

So the following code if called from different processes (or threads) on the same host prints always the same id:

#include "zhelpers.hpp"

int main(){
    zmq::context_t context(1);
    zmq::socket_t client(context, ZMQ_REQ);

    std::cout << s_set_id(client) << std::endl;
    return 0;
}

Suggested fix: add srand(time(NULL)) at the beginning of s_set_id (zmq::socket_t &) body in C++/examples/zhelpers.hpp

@myd7349
Copy link
Contributor

myd7349 commented Aug 14, 2015

@radome
You should call srand only once in your program. Please refer this question on stackoverflow: Same random numbers every loop iteration.

For the same reason, we can not put the call to srand in s_set_id(Someone may call s_set_id from multiple threads or in a for loop). Instead, we should call srand ourselves at the beginning of the program. Just like most of the examples do(rtdealer.c#L59, for instance).

You may refactor your code like this:

#include "zhelpers.hpp"

int main(){
    zmq::context_t context(1);
    zmq::socket_t client(context, ZMQ_REQ);

    srandom((unsigned)random(NULL));

    std::cout << s_set_id(client) << std::endl;
    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants