IO进程(学习)2024.8.20

目录

线程同步

同步概念

信号量

信号量的特性

信号量的分类

1.posix信号量

2.System V信号量

函数接口

1.初始化信号量

2.申请资源(p操作)

3.释放资源(V操作)

线程互斥

互斥概念

互斥锁

函数接口

死锁

条件变量

线程同步

同步概念

多个线程按照约定的顺序相互配合完成一件事

信号量

通过信号量实现线程间同步。

信号量:由信号量来决定线程是继续运行还是阻塞等待,信号量代表某一类资源,其值表示系统中该资源的数量
信号量是一个受保护的变量,只能通过三种操作来访问:初始化、P操作、V操作
信号量的值为非负整数

信号量的特性

P操作(申请资源):
        当信号量的值大于0时,可以申请到资源,申请资源后信号量的值减1
        当信号量的值等于0时,申请不到资源,函数阻塞
V操作(释放资源):
        不阻塞,执行到释放操作,信号量的值加1

信号量的分类

1.posix信号量

        (1)无名信号量:数据存储在内存中,通常在线程间使用或父子进程间
                函数接口:sem_init\sem_wait\sem_post

        (2)有名信号量:数据存储在文件中,在进程间线程间都可以使用
                函数接口:sem_open\sem_wait\sem_post\sem_close

2.System V信号量

        System V是信号量的集合,叫信号灯集,属于IPC对象
                函数接口:semget\semctl\semop

函数接口

1.初始化信号量

#include <semaphore.h>

int  sem_init(sem_t *sem,  int pshared,  unsigned int value)  
功能:初始化信号量(在代码中可以定义多个信号量,通过它可以区分不同的信号量)
参数:sem:初始化的信号量对象  

           pshared:信号量共享的范围(0: 线程间使用        1:进程间使用)
           value:信号量初值
返回值:成功   0
              失败   -1

#include <stdio.h>
#include <semaphore.h>

int main(int argc, char const *argv[])
{
    sem_t sem;
    if (sem_init(&sem, 0, 1) < 0)
    {
        perror("sem_init函数创建失败");
        return -1;
    }
    return 0;
}

2.申请资源(p操作)

int  sem_wait(sem_t *sem)  
功能:申请资源  P操作 
参数:sem:信号量对象
返回值:成功 0
              失败 -1
注:此函数执行过程,当信号量的值大于0时,表示有资源可以用,则继续执行,同时对信号量减1;当信号量的值等于0时,表示没有资源可以使用,函数阻塞

#include <stdio.h>
#include <semaphore.h>

int main(int argc, char const *argv[])
{
    sem_t sem;
    if (sem_init(&sem, 0, 1) < 0)
    {
        perror("sem_init函数创建失败");
        return -1;
    }
    // 申请资源 P操作
    sem_wait(&sem); // 0
    printf("hello\n");

    sem_wait(&sem); // 进入阻塞状态,只打印hello
    printf("world\n");

    return 0;
}

3.释放资源(V操作)

int  sem_post(sem_t *sem)   
功能:释放资源  V操作      
参数:sem:信号量对象
返回值:成功 0
               失败 -1
注:释放一次信号量的值加1,函数不阻塞

#include <stdio.h>
#include <semaphore.h>

int main(int argc, char const *argv[])
{
    sem_t sem;
    if (sem_init(&sem, 0, 1) < 0) // sem=1
    {
        perror("sem_init函数创建失败");
        return -1;
    }
    // 申请资源 P操作
    sem_wait(&sem); // sem=0
    printf("hello ");

    // 释放资源 V操作
    sem_post(&sem); // sem=1

    sem_wait(&sem); // 不进入阻塞状态,打印hello world
    printf("world\n");

    return 0;
}

线程互斥

互斥概念

多个线程访问临界资源时,同一时间只能一个线程访问
        临界资源:多个线程共同访问的数据,且一次仅允许一个进程所使用的资源

互斥锁

通过互斥锁可以实现互斥机制,主要用来保护临界资源,每个临界资源都由一个互斥锁来保护,线程必须先获得互斥锁才能访问临界资源,访问完资源后释放该锁。如果无法获得锁,线程会阻塞直到获得锁为止。
互斥锁的操作方式:1.初始化
                                 2.申请锁(上锁):阻塞  

                                        当申请不到锁时(表示锁被其他线程占用),线程是阻塞的
                                 3.释放锁(解锁):非阻塞
注意:上锁和解锁需要成对出现

函数接口

#include <pthread.h>
int  pthread_mutex_init(pthread_mutex_t * mutex, pthread_mutexattr_t *attr) 
功能:初始化互斥锁
参数:mutex:互斥锁
           attr:  互斥锁属性  // 一般设置为NULL
返回值:成功 0
              失败 -1
      
int  pthread_mutex_lock(pthread_mutex_t *mutex)   
功能:申请互斥锁     
参数:mutex:互斥锁
返回值:成功 0
              失败 -1

int  pthread_mutex_unlock(pthread_mutex_t *mutex)   
功能:释放互斥锁     
参数:mutex:互斥锁
返回值:成功 0
              失败 -1

int  pthread_mutex_destroy(pthread_mutex_t  *mutex)  
功能:销毁互斥锁     
参数:mutex:互斥锁

pthread_mutex_lock和pthread_mutex_trylock区别

pthread_mutex_lock是阻塞的;
pthread_mutex_trylock不阻塞,如果申请不到锁会立刻返回

案例:两个线程,一个线程倒置全局数组中的数,另一个线程遍历数组中数据,每隔1s打印一次

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

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

void *daozhi(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 *bianli(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 t1, t2;
    if (pthread_create(&t1, NULL, daozhi, NULL) != 0)
    {
        perror("pthread_create创建倒置线程失败");
        return -1;
    }
    if (pthread_create(&t2, NULL, bianli, NULL) != 0)
    {
        perror("pthread_create创建遍历线程失败");
        return -1;
    }
    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        perror("创建互斥锁失败");
        return -1;
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_mutex_destroy(&lock);

    return 0;
}

死锁

死锁是指两个或两个以上的进程/线程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。

死锁产生的四个必要条件:
1.互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
2.不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
3.请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
4.循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。

注意:当上述四个条件都成立的时候,便形成死锁。当然,死锁的情况下如果打破上述任何一个条件,便可让死锁消失。

条件变量

条件变量和互斥锁搭配使用,实现同步操作
初始化:pthread_cond_init
等待条件变量产生:pthread_cond_wait
产生条件变量:pthread_cond_signal


int pthread_cond_init(pthread_cond_t *cond,  const pthread_condattr_t * attr);
功能:初始化条件变量
参数:cond:是一个指向结构pthread_cond_t的指针
           restrict attr:是一个指向结构pthread_condattr_t的指针,一般设为NULL
返回值:成功:0

              失败:非0

int pthread_cond_wait(pthread_cond_t * cond, pthread_mutex_t restrict *mutex);
功能:等待条件变量的产生
参数:restrict cond:要等待的条件
           restrict mutex:对应的锁
返回值:成功:0

              失败:非0

int pthread_cond_signal(pthread_cond_t *cond);
功能:产生条件变量
参数:cond:条件变量值
返回值:成功:0

              失败:非0

1.当没有条件产生时pthread_cond_wait函数会阻塞,同时会将锁解开;如果等待到条件产生,函数会结束阻塞同时进行上锁.
2.pthread_cond_wait阻塞状态是等待pthread_cond_signal唤醒.
3.pthread_cond_signal只能唤醒单个cond_wait,相当于一对一;

   pthread_cond_broadcast可以唤醒多个cond_wait,相当于一对多

案例:两个线程,一个线程倒置全局数组中的数,另一个线程遍历数组中数据,每隔1s打印一次。要求:实现倒置一次,打印一次,顺序执行

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

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

void *daozhi(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&lock); // 上锁
        if (flag == 1)
        {
            pthread_cond_wait(&cond1, &lock);
        }
        for (int i = 0; i < 5; i++)
        {
            int t = a[i];
            a[i] = a[9 - i];
            a[9 - i] = t;
        }
        flag = 1;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&lock); // 解锁
    }
    return NULL;
}

void *bianli(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&lock); // 上锁
        if (flag == 0)
        {
            pthread_cond_wait(&cond, &lock);
        }
        for (int i = 0; i < 10; i++)
        {
            printf("%d ", a[i]);
        }
        printf("\n");
        flag = 0;
        pthread_cond_signal(&cond1);
        pthread_mutex_unlock(&lock); // 解锁
        sleep(1);
    }
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t t1, t2;
    if (pthread_create(&t1, NULL, daozhi, NULL) != 0)
    {
        perror("pthread_create创建倒置线程失败");
        return -1;
    }
    if (pthread_create(&t2, NULL, bianli, NULL) != 0)
    {
        perror("pthread_create创建遍历线程失败");
        return -1;
    }
    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        perror("创建互斥锁失败");
        return -1;
    }
    if (pthread_cond_init(&cond, NULL) != 0)
    {
        perror("初始化条件变量失败");
        return -1;
    }
    if (pthread_cond_init(&cond1, NULL) != 0)
    {
        perror("初始化条件变量失败");
        return -1;
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_mutex_destroy(&lock);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值