多线程下的随机数初始化 srand()

来源:互联网 发布:linux tcp发送窗口 编辑:程序博客网 时间:2024/05/20 21:44
今天在调试程序时候发现某个线程中的 rand() 随机函数每次运行都返回同一个数据,检查了程序,在程序中也调用了 srand(GetTicketCount()) 来初始化随机数生成器,那为什么每次运行结果还一样呢???

后来发现,这个问题和多线程有关,跟踪 srand 和 rand 的函数内部后发现,其实 srand 和 rand 内部是使用了TlsGetValue等函数来存储随机数种子了,也就是说,这个随机数种子对每个线程都需要初始化一次 srand,而以前的代码是在主线程中初始化了一次,当然每次的结果都一样了。



void __cdecl srand (
unsigned int seed
)
{
#ifdef _MT

_getptd()->_holdrand = (unsigned long)seed;

#else /* _MT */
holdrand = (long)seed;
#endif /* _MT */
}

_ptiddata __cdecl _getptd (
void
)
{
_ptiddata ptd;
DWORD TL_LastError;


TL_LastError = GetLastError();
if ( (ptd = TlsGetValue(__tlsindex)) == NULL ) {
/*
* no per-thread data structure for this thread. try to create
* one.
*/
if ( ((ptd = _calloc_crt(1, sizeof(struct _tiddata))) != NULL) &&
TlsSetValue(__tlsindex, (LPVOID)ptd) ) {

/*
* Initialize of per-thread data
*/

_initptd(ptd);

ptd->_tid = GetCurrentThreadId();
ptd->_thandle = (unsigned long)(-1L);
}
else
_amsg_exit(_RT_THREAD); /* write message and die */
}

SetLastError(TL_LastError);


return(ptd);
}
0 0
原创粉丝点击