线程安全与线程不安全

基本概念

线程不安全:就是不提供数据访问保护,在多线程环境中对数据进行修改,会出现数据不一致的情况。

线程安全:就是多线程环境中有对全局变量的变动时,需要对执行的代码块采用锁机制,当一个线程访问到某个数据时,其他线程需要等待当前线程执行完该代码块才可执行,不会出现数据不一致或者数据被污染。

如果一段代码在被多个线程执行,如果每次运行结果和单线程运行的结果是一样的,而且其他变量的值和预期一样,就是线程安全的。

线程安全主要由对有全局变量或静态变量有修改动作而引起的。

小实验

描述:

首先创建两个线程,执行同一段代码对全局变量count进行修改操作,这里是进行++5000次并打印,我们预期的结果应该是10000,分别在线程安全和线程不安全运行对比。

我们在读取变量的值和把变量的新值保存回去,这两个之间插入一个printf调用,它会调用write系统调用,此时会从用户态进入内核态,为内核调度别的线程执行提供了一个很好的时机。

线程不安全

#include <stdio.h>
#include <pthread.h>

int count = 1;

void* run(void * arg1)
{
    int i = 0;
    while(1)
    {
        int val = count;
        i++;
        printf("count is %d  \n", count);
        count = val+1;
        if(5000 == i)
            break;
    }
}


int main()
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, run, NULL);
    pthread_create(&tid2, NULL, run, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    return 0;
}

重复执行执行多次观察结果:
第一次

1
第二次
2

我们发现在线程不安全的情况下,执行结果不符合预期。

线程安全下:

#include <stdio.h>
#include <pthread.h>

int count = 1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* run(void * arg1)
{
    int i = 0;
    pthread_mutex_lock(&mutex);
    while(1)
    {
        int val = count;
        i++;
        printf("count is %d  \n", count);
        count = val+1;
        if(5000 == i)
            break;
    }
    pthread_mutex_unlock(&mutex);
}


int main()
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, run, NULL);
    pthread_create(&tid2, NULL, run, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    return 0;
}

我们通过引入互斥锁(Mutex),使得一个时刻只能有一个线程进入代码块,从而达到线程安全的目的。

结果:
1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值