whether rand_r is real thread safe?

后端 未结 3 1727
野性不改
野性不改 2020-12-09 00:26

Well, rand_r function is supposed to be a thread safe function. However, by its implementation, I cannot believe it could make itself not change by other threads. Suppose th

3条回答
  •  死守一世寂寞
    2020-12-09 01:00

    rand_r is thread safe is because the function is entirely pure. It doesn't read or modify any state other than the arguments. It can therefore be safely called concurrently.

    This is different from most rand functions that hold the state (the seed) in a global variable.

    Suppose that two threads will invoke rand_r in the same time with the same variable seed.

    I am assuming you mean something like this

    int globalSeed;
    
    //thread 1
    rand_r(&globalSeed);
    
    //thread 2
    rand_r(&globalSeed);
    

    That doesn't mean that the function isn't thread safe, that just means you are using it in a non thread safe way by supplying an output parameter that may be accessed/modified by another thread.

    It is the same thing as writing the function result to a global variable that may be accessed/modified by the another thread. It doesn't mean the function isn't thread safe, it means your code isn't thread safe.

提交回复
热议问题