Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15183199
  • 博文数量: 7460
  • 博客积分: 10434
  • 博客等级: 上将
  • 技术积分: 78178
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-02 22:54
文章分类

全部博文(7460)

文章存档

2011年(1)

2009年(669)

2008年(6790)

分类: C/C++

2008-05-25 20:50:25

今天在调试程序时候发现某个线程中的 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);
}

阅读(242) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~