基本概念
线程不安全:就是不提供数据访问保护,在多线程环境中对数据进行修改,会出现数据不一致的情况。
线程安全:就是多线程环境中有对全局变量的变动时,需要对执行的代码块采用锁机制,当一个线程访问到某个数据时,其他线程需要等待当前线程执行完该代码块才可执行,不会出现数据不一致或者数据被污染。
如果一段代码在被多个线程执行,如果每次运行结果和单线程运行的结果是一样的,而且其他变量的值和预期一样,就是线程安全的。
线程安全主要由对有全局变量或静态变量有修改动作而引起的。
小实验
描述:
首先创建两个线程,执行同一段代码对全局变量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;
}
重复执行执行多次观察结果:
第一次
第二次
我们发现在线程不安全的情况下,执行结果不符合预期。
线程安全下:
#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),使得一个时刻只能有一个线程进入代码块,从而达到线程安全的目的。
结果: