多条线程对同一个变量操作,有可能会同时修改了这个变量的值,导致线程不安全
如下线程就是不安全的
这3条线程都对a进程操作,如果t1线程把a减到了0,那么下一次进入while(0>0)就不满足,但是有可能其他线程在t1线程执行了a-- 使得a=0的时候切换了,进入了运行态,并且它又是刚好运行切换的点是a–,那么a会变成-1,这就导致线程不安全了。所以需要有一个保护机制,保护a变量被线程操作的时候,不能发生任务切换,就需要加锁。
不安全线程
#include <stdio.h>
#include <pthread.h>
int a=100;
void sub()
{
while (a>0)
{
a--;
printf("sub %d\n",a);
}
}
int main(int argc, char **argv)
{
pthread_t t1,t2,t3;
pthread_create(&t1,NULL,sub,NULL);
pthread_create(&t2,NULL,sub,NULL);
pthread_create(&t3,NULL,sub,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
while(1);
return 0;
}
没有互斥锁运行程序
#include <stdio.h>
#include <pthread.h>
int a=100;
void sub()
{
while (a>0)
{
a--;
printf("sub %d\n",a);
}
}
int main(int argc, char **argv)
{
pthread_t t1,t2,t3;
pthread_create(&t1,NULL,sub,NULL);
pthread_create(&t2,NULL,sub,NULL);
pthread_create(&t3,NULL,sub,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
while(1);
return 0;
}
这可以看出a的值出输出不是按顺序减少,因为存在多个线程在做减法。
添加互斥锁
1、pthread_mutex_t lock; 定义互斥锁
2、 pthread_mutex_init(&lock,NULL);//初始化锁
3、pthread_mutex_lock( &lock ) ; 在需要保护代码段上锁
4、 pthread_mutex_unlock( &lock ) ; 解锁
5、pthread_mutex_destroy(&lock); 销毁锁
有互斥锁
#include <stdio.h>
#include <pthread.h>
int a=100;
pthread_mutex_t lock;
void sub()
{
pthread_mutex_lock( &lock ) ;
while (a>0)
{
a--;
printf("sub %d\n",a);
}
pthread_mutex_unlock( &lock ) ;
}
int main(int argc, char **argv)
{
pthread_t t1,t2,t3;
pthread_mutex_init(&lock,NULL);//初始化锁
pthread_create(&t1,NULL,sub,NULL);
pthread_create(&t2,NULL,sub,NULL);
pthread_create(&t3,NULL,sub,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
while(1);
pthread_mutex_destroy(&lock);
return 0;
}