Linux高阶——1110—线程安全问题&&解决方法

1、同步、异步、阻塞、非阻塞

同步过程:发起调用,调用者需要等待被调用者的结果

异步过程:发起调用,无需等待被调用的结果,当有结果后,此结果传出,无需主动获取

阻塞和非阻塞:发起到产生结果,中间的等待过程

阻塞:放弃cpu

非阻塞:不放弃cpu

2、线程安全问题

1、多线程访问互斥

多线程访问共享数据,引发冲突和异常,例如多个线程操作共享数据结构体,全局变量,磁盘文件等

举例:a=0;a++

a++的操作,汇编指令需要三句:内存取值0,自增1,回写1

当寄存器还未回写成功之前,寄存器中的值仍为0,因此另一个线程在取值时,取到的可能是还未回写成功的1,而是还未自增前的0

结果:多线程访问a,应该是一个累加过程,但是因为访问冲突,导致最终的结果比预期结果小

结果截图:问题不明显,但是有问题

如果中间引入变量,则问题更明显,结果相差更多

解决方法1:互斥锁

1、互斥锁使用目的

互斥锁是用来保护代码段的,一般代码段是用来访问全局变量的

一般只对访问读写全局数据的代码上锁

2、互斥锁的使用范围

上锁与解锁之间的代码,被称为临界区代码,是被互斥保护的

无论有多少线程,临界区代码只允许单独访问,其他线程只能等待

pthread_mutex_t lock

3、互斥锁的性质

多个线程争夺一把锁,利用一把锁来保护代码段,锁具有互斥性,只有一个线程可以使用这把互斥锁, 其余线程需要等待

互斥锁的系统里存在一个等待队列,称为互斥等待队列,进入到等待队列中的线程均为阻塞态

当当前占用锁的线程结束,下一个使用锁的线程确定方式:

1、争夺访问,当锁被解除占用,唤醒所有等待线程,争夺资源

但是可能引起惊群问题:资源有限的情况下,多个线程争夺资源,但是只有少数线程可以获取,那些没有抢到的线程付出的开销没有意义

2、预分配

避免惊群问题,在等待的线程中分配唤醒标记,只有被标记的线程,资源释放后才能被唤醒使用资源

3、就近原则

提高资源的使用效率,如果线程解锁后立即请求,同时满足条件(时间片充裕),依然是此线程占用

4、互斥锁的函数使用

pthread_mutex_t lock——互斥锁类型

lock=PTHREAD_MUTEX_INITIALIZER——静态初始化

pthread_mutex_init(&lock,NULL)——动态初始化

pthread_mutex_destroy(&lock)——释放互斥锁

pthread_mutex_lock(&lock)——上锁请求,阻塞模式下,如果资源被占用,则等待

pthread_mutex_unlock(&lock)——解锁

解决代码

一般习惯将锁设在for循环内部

写端上锁的原因:两个线程同时写入,容易造成相互覆盖

读端上锁的原因:如果一端为读端,一端为写端,可能造成读到的是刚写入的数据

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<pthread.h>
#include<pthread.h>

#define FLAG 5000
int a;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

void * busines(void* arg)
{
    int tmp;
    for(int i=0;i<FLAG;i++)
    {   
        pthread_mutex_lock(&lock);
        tmp=a;
        printf("thread 0x%x ++a %d\n",(int)pthread_self,++tmp);
        a=tmp;
        pthread_mutex_unlock(&lock);
    }   
}

int main()
{
    pthread_t tids[2];
    int i;
    for(i=0;i<2;i++)
    {   
        pthread_create(&tids[i],NULL,busines,NULL);
    }   
    while(i--)
    {   
        pthread_join(tids[i],NULL);
    }   
    return 0;
}

成功截图

解决方法2:读写锁

1、读写锁的性质

读写锁在互斥锁的基础上修改,它满足多读场景,如果用户要读取数据可以使用读锁访问,如果用户要修改数据使用写锁访问

读共享,写独占,读写互斥

写锁与互斥锁一致,为独占锁

如果要提高资源的读访问效果,可以先采用读写锁,避免使用互斥锁

2、读写锁的函数使用

pthread_rwlock_t lock——读写锁类型

lock=PTHREAD_RWLOCK_INITIALIZER——静态初始化

pthread_rwlock_init(&lock,NULL)——动态初始化

pthread_rwlock_destroy(&lock)——释放锁

pthread_rwlock_rdlock(&lock)——上读锁

pthread_rwlock_wrlock(&lock)——上写锁

pthread_mutex_unlock(&lock)——解锁

读写锁代码

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<pthread.h>
#include<pthread.h>

#define FLAG 5000
int code;
pthread_rwlock_t lock=PTHREAD_RWLOCK_INITIALIZER;

void * rd_busines(void* arg)
{
    while(1)
    {   
        pthread_rwlock_rdlock(&lock);
        printf("rd thread 0x%x ,  %d\n",(int)pthread_self(),code);
        pthread_rwlock_unlock(&lock);
        usleep(3000000);
    }   
}

void * wr_busines(void* arg)
{
    while(1)
    {   
        pthread_rwlock_wrlock(&lock);
        printf("wr thread 0x%x , ++ %d\n",(int)pthread_self(),++code);
        pthread_rwlock_unlock(&lock);
        usleep(3000000);
    }   
}

int main()
{
    pthread_t tids[8];
    int i;
    for(i=0;i<3;i++)
    {
        pthread_create(&tids[i],NULL,wr_busines,NULL);
    }
    for(i=0;i<3;i++)
    {
        pthread_create(&tids[i],NULL,rd_busines,NULL);
    }

    while(i--)
    {
        pthread_join(tids[i],NULL);
    }
    return 0;
}

 成功截图

3、进程可以使用的互斥锁

并发访问冲突不局限于线程,进程也有

进程可以用的互斥锁:根据修改互斥锁属性,将线程变为进程,可以多进程使用,避免访问异常

函数使用

pthread_mutexattr_t attr——互斥锁属性

pthread_mutex_attr_init(&attr)——初始化属性,默认线程锁

pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED)——将互斥锁属性中的锁的状态变为进程锁

pthread_mutexattr_destroy(&attr)——释放互斥锁属性

pthread_mutex_init(&lock,&attr)——初始化锁时使用自定义属性

代码
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<pthread.h>
#include<pthread.h>
#include<sys/mman.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/fcntl.h>

typedef struct
{
    int code;
    pthread_mutex_t lock;
}shared_t;

int main()
{
    int fd;
    shared_t* ptr;
    fd=open("process_map",O_RDWR);
    ftruncate(fd,sizeof(shared_t));

    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);
    ptr=mmap(NULL,sizeof(shared_t),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    pthread_mutex_init(&ptr->lock,&attr);
    ptr->code=0;
    pid_t pid;
    pid=fork();
    if(pid>0)
    {
        for(int i=0;i<5000;i++)
        {
            pthread_mutex_lock(&ptr->lock);
            printf("parent %d,++code %d\n",getpid(),++ptr->code);
            pthread_mutex_unlock(&ptr->lock);
        }
        wait(NULL);
        pthread_mutex_destroy(&ptr->lock);
        pthread_mutexattr_destroy(&attr);
        munmap(ptr,sizeof(shared_t));
    }
    else if(pid==0)
    {
        for(int i=0;i<5000;i++)
        {
            pthread_mutex_lock(&ptr->lock);
            printf("child %d,++code %d\n",getpid(),++ptr->code);
            pthread_mutex_unlock(&ptr->lock);
        }
        exit(0);
    }
    else
    {
        perror("fork call failed");
        exit(0);
    }
    return 0;
}
正确截图

2、线程控制与调度线程同步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值