多线程中使用mktime和setenv函数
生活随笔
收集整理的這篇文章主要介紹了
多线程中使用mktime和setenv函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在編寫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
總結
以上是生活随笔為你收集整理的多线程中使用mktime和setenv函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何从ATS获取客户端平均响应时间(单位
- 下一篇: 在ATS插件中使用互斥锁