众所周知,C语言中,srand()是设置随机数种子,rand()生成随机数,C中生成的实际是伪随机数,即相同的种子开始生成的是相同的数列。
VC下(其他环境没看过代码,不能保证),srand是线程无关的,即一个线程里设置随机数种子不会影响另外一个线程里的随机数生成(测试代码在最后面)。原因参见srand代码(在VC安装下的rand.c):
当初C语言设计的时候,还没有考虑到线程的问题,不知道其他编译环境是不是也有类似的机制。
测试代码(只在VC下测试过):
执行结果:
Thread 1: the first 10 random numbers:
41 18467 6334 26500 19169 15724 11478 29358 26962 24464
Thread 2: the seed has been changed to 1
Thread 1: the second 10 random numbers:
5705 28145 23281 16827 9961 491 2995 11942 4827 5436
x
Press any key to continue
如果执行测试代码第16行,结果则是:
Thread 1: the first 10 random numbers:
41 18467 6334 26500 19169 15724 11478 29358 26962 24464
Thread 2: the seed has been changed to 1
Thread 1: the second 10 random numbers:
41 18467 6334 26500 19169 15724 11478 29358 26962 24464
x
Press any key to continue