Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c++ - whether rand_r is real thread safe?

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 that two threads will invoke rand_r in the same time with the same variable seed. So read-write race will occur. The code rand_r implemented by glibc is listed below. Anybody knows why rand_r is called thread safe?

 int
    rand_r (unsigned int *seed)
    {
      unsigned int next = *seed;
      int result;

      next *= 1103515245;
      next += 12345;
      result = (unsigned int) (next / 65536) % 2048;

      next *= 1103515245;
      next += 12345;
      result <<= 10;
      result ^= (unsigned int) (next / 65536) % 1024;

      next *= 1103515245;
      next += 12345;
      result <<= 10;
      result ^= (unsigned int) (next / 65536) % 1024;

      *seed = next;

      return result;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can think of three levels of thread safety, which I'll number here for ease of reference.

1) Not thread safe at all. It is unsafe to call the function concurrently from multiple threads. For example, strtok.

2) Thread safe with respect to the system. It is safe to call the function concurrently from multiple threads, provided that the different calls operate on different data. For example, rand_r, memcpy.

3) Thread safe with respect to data. It is safe to call the function concurrently from multiple threads, even acting on the same data. For example pthread_mutex_lock.

rand_r is at level 2, and the convention in the context of C (in particular in the POSIX specification) is to call this "thread safe".

In some other languages, such as Java, the convention is to refer to level 3 as "thread safe" and everything else as "not thread safe". So for example java.util.Vector is "thread safe" and java.util.ArrayList is "not thread safe". Of course all the methods of java.util.ArrayList are at level 2. So a programmer coming from Java might naturally call rand_r and memcpy "not thread safe".

In C the convention is different, perhaps because internally synchronised data structures are fairly rare to begin with. In the context of C you might ask "are file handles thread-safe?", and be talking about level 3, but when asking "is this function thread-safe?" that generally means level 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...