在编写ATS插件的过程中,发现使用mktime会偶尔出现段错误, 经过网上调研,发现mktime等函数不是线程安全的, 于是编写下面的代码进行测试.
注意加锁和不加锁区别很大, 在mktime中使用多线程, 加上互斥锁就没有问题.
//gcc -g mktime_multithread.c -o mktime_multithread -lpthread -std=c99
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex;
void* test_setenv(void *arg)
{
char ac_name[1024] = {};
for (int i = 0; i < 10000; i++)
{
snprintf(ac_name, sizeof(ac_name), "stra_1_fe_filter_dt_other_hadoop_arg_%d", i);
printf("setenv %s\n",ac_name);
pthread_mutex_lock(&mutex);
setenv(ac_name," 1500",0);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* test_mktime(void* arg){
for (int i = 0; i < 10000; i++)
{
/*测试非法日期会不会导致程序异常*/
struct tm st_tm;
memset(&st_tm,0,sizeof(st_tm));
strptime("201506270828001","%Y%m%d%H%M",&st_tm);
pthread_mutex_lock(&mutex);
time_t st_time = mktime(&st_tm);
pthread_mutex_unlock(&mutex);
printf("time_t=%lu\n",st_time);
}
return NULL;
}
int main(int argc, char* argv[])
{
pthread_mutex_init(&mutex,NULL);
pthread_t pt[2] = {0};
pthread_create(&pt[0], NULL, test_setenv, NULL);
pthread_create(&pt[1], NULL, test_mktime, NULL);
pthread_join(pt[0], NULL);
pthread_join(pt[1], NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
参考文献
[1].http://www.xuebuyuan.com/1824402.html