localtime_r在多线程环境下可能存在死锁

来源:互联网 发布:怎么在origin显示数据 编辑:程序博客网 时间:2024/05/22 00:31

 localtime_r是localtime的线程安全版本,在localtime的手册中描述如下:
Attention: Do not use the ctime, localtime, gmtime, or asctime subroutine in a multithreaded
            environment
. See the multithread alternatives in the ctime_r (ctime_r,localtime_r, gmtime_r, or
            asctime_r Subroutine), localtime_r, gmtime_r, or asctime_r subroutine article.

         但是在某些情况下,localtime_r可能存在死锁的情况,使用如下的测试程序:

       #include <pthread.h>
#include <time.h>

       void *mytest(void *arg)
{
        pthread_detach(pthread_self());

               time_t current;
        struct tm date;
        time(&current);

               while (1) {
                localtime_r(&current, &date);
                printf("OK/n");
        }
}

       int main()
{
        int i = 0;
        pthread_t tid[10];

               for (i = 0; i < 10; i++) {
                pthread_create(&tid[i], NULL, mytest, NULL);
        }

               sleep(1);

               pthread_cancel(tid[0]);
        pthread_cancel(tid[1]);
        pthread_cancel(tid[2]);
        pthread_cancel(tid[3]);

                while (1)
                sleep(100000000);
}

         运行该测试程序, 大约1秒之后, 屏幕不再输出任何信息,使用dbx跟踪程序如下:
(dbx) thread
 thread  state-k     wchan            state-u    k-tid mode held scope function
 $t1     wait      0xf100060027c244b0 running  7172309   k   no   sys  nsleep           
*$t2     run                          blocked  7176385   k   no   sys  _global_lock_common
 $t3     wait      0x000000011000ad18 blocked  3379347   k   no   sys  _rec_mutex_lock  
 $t4     zomb                         terminated 7180483   k   no   sys  pthread_exit     
 $t5     wait      0x000000011000ad18 blocked  9109677   k   no   sys  _rec_mutex_lock  
>$t6     wait      0x000000011000ad18 blocked  3498171   k   no   sys  _rec_mutex_lock  
 $t7     wait      0x000000011000ad18 blocked  3502269   k   no   sys  _rec_mutex_lock  
 $t8     wait      0x000000011000ad18 blocked  3506367   k   no   sys  _rec_mutex_lock  
 $t9     wait      0x000000011000ad18 blocked  2384027   k   no   sys  _rec_mutex_lock  
 $t10    wait      0x000000011000ad18 blocked  2932903   k   no   sys  _rec_mutex_lock  
 $t11    wait      0x000000011000ad18 blocked  2494699   k   no   sys  _rec_mutex_lock  
(dbx) where
_rec_mutex_lock(??) at 0x900000000028f90
localtime_tz_r(??, ??, ??) at 0x900000000055644
mytest(0x0) at 0x1000005fc

所有的线程都在试图获取锁,进程处于死锁状态。目前AIX工程师给出的临时解决方案是将环境变量TZ设置为BEIST,
export TZ=BEIST
之后再运行测试程序就没有死锁的现象。由于TZ是一个系统环境变量,修改之后可能会引起其他系统出问题.
原创粉丝点击