多线程中使用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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值