io 互斥

概念

互斥:多个线程在访问临界资源时,同一时间只能一个线程访问

临界资源:一次仅允许一个线所使用的资源

临界区:指的是一个访问共享资源的程序片段

互斥锁(mutex):通过互斥锁可以实现互斥机制,主要用来保护临界资源,每个临界资源都由一个互斥锁来保护,线程必须先获得互斥锁才能访问临界资源,访问完资源后释放该锁。如果无法获得锁,线程会阻塞直到获得锁为止。

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

int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
pthread_mutex_t lock;

void *handler_swap(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&lock);  //上锁
        for (int i = 0; i < 5; i++)
        {
            int t = a[i];
            a[i] = a[9 - i];
            a[9 - i] = t;
        }
        pthread_mutex_unlock(&lock); //解锁
    }
    return NULL;
}

void *handler_print(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&lock); //上锁
        for (int i = 0; i < 10; i++)
            printf("%d ", a[i]);
        printf("\n");
        pthread_mutex_unlock(&lock); //解锁
        sleep(1); //锁里面减少耗时大的操作
    }
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid1, tid2;

    //初始化互斥锁
    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        perror("lock err");
        return -1;
    }

    if (pthread_create(&tid1, NULL, handler_swap, NULL) != 0)
    {
        perror("err");
        return -1;
    }

    if (pthread_create(&tid2, NULL, handler_print, NULL) != 0)
    {
        perror("err");
        return -1;
    }

    pthread_join(tid1, NULL); //为了让整个进程不要结束
    pthread_join(tid2, NULL);

    return 0;
}

死锁产生的四个必要条件

1、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用

  1. 不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
  2. 请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
  3. 循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值