IO进程(线程篇)

知识点链接

https://www.yuque.com/aihenaobaijin/camuoq/lscmvf6z1arklau4?singleDoc# 《IO进程》

建议先学习知识点,再进行下面的练习

线程

概念

线程是一个轻量级的进程,为了提高系统的性能引入线程

线程和进程是参与统一的调度

在同一个进程中可以创建的多个线程,共享进程资源

线程资源

共享的资源:可执行的指令、静态数据、进程中打开的文件描述符、信号处理函数、当前工作目录、用户ID、用户组ID

私有的资源:线程ID (TID)、PC(程序计数器)和相关寄存器、堆栈(局部变量, 返回地址)、错误号 (errno)、信号掩码和优先级、执行状态和属性

 练习:循环输入输出,quit结束

通过线程实现数据的交互,主线程循环从终端输入,线程函数将数据循环输出,当输入quit结束程序。

1)全局变量进行通信

2)加上标志位(flag),实现主线程输入一次,线程函数打印一次, int flag = 0;

#include <stdio.h>
#include <pthread.h>
#include <string.h>
char s[32];
int flag = 0; //为了进行线程间通讯,保证主线程先输入然后从线程再输出

void *handler_thread(void *arg)
{
    while (1)
    {
        if (flag == 1) //主线程输入完将flag置1从线程再输出
        {
            if (strcmp(s, "quit") == 0)
                break;
            printf("%s\n", s);
            flag--;
        }
    }
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler_thread, NULL) > 0)
    {
        perror("err");
        return -1;
    }

    while (1)
    {
        //scanf前也可以不加if判断,利用阻塞时间让从线程输出
        // if (flag == 0)  //从线程输出完将flag置0主线程再输入
        // {
            scanf("%s", s);
            flag++;

            if (strcmp(s, "quit") == 0)
                break;
        // }
    }
}

同步

概念

同步(synchronization)指的是多个任务(线程)按照约定的顺序相互配合完成一件事情(异步:异步则反之,并非一定需要一件事做完再做另一件事)

同步机制

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

信号量:通过信号量实现同步操作;由信号量来决定线程是继续运行还是阻塞等待。

信号量代表某一类资源,其值表示系统中该资源的数量:

信号量的值>0, 表示有资源可以用, 可以申请到资源。

信号量的值<=0, 表示没有资源可以用, 无法申请到资源, 阻塞。

信号量还是一个受保护的变量,只能通过三种操作来访问:初始化、P操作(申请资源)、V操作(释放资源)

sem_init:信号量初始化

sem_wait:申请资源,P操作,如果没有资源可以用会阻塞等待,直到有资源可用结束阻塞资源-1。

sem_post:释放资源,V操作,非阻塞,资源+1。

练习:用信号量实现循环输入输出quit结束

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

char s[32];
sem_t sem1; //信号量对象
sem_t sem2;

void *handler_thread(void *arg)
{
    while (1)
    {

        //申请资源 sem1
        sem_wait(&sem1);
        if (strcmp(s, "quit") == 0)
            break;
        printf("%s\n", s);
        //释放资源sem2
        sem_post(&sem2);
    }
    return NULL;
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    //初始化信号量
    if (sem_init(&sem1, 0, 0) != 0)
    {
        perror("sem_init err");
        return -1;
    }

    if (sem_init(&sem2, 0, 1) != 0)
    {
        perror("sem_init err");
        return -1;
    }

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

    while (1)
    {
        //申请资源sem2
        sem_wait(&sem2);
        scanf("%s", s);
        //释放资源sem1
        sem_post(&sem1);
        if (strcmp(s, "quit") == 0)
            break;
    }
}

互斥

概念

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

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

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

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

pthread_mutex_init:初始化互斥锁

pthread_mutex_lock:申请互斥锁

pthread_mutex_unlock:释放互斥锁

pthread_mutex_destroy:销毁互斥锁

 练习:打印倒置数组功能

#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、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用

2、 不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。

3、 请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。

4、 循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。

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

 条件变量

条件变量(cond)用于在线程之间传递信号,以便某些线程可以等待某些条件发生。当某些条件发生时,条件变量会发出信号,使等待该条件的线程可以恢复执行。

一般和互斥锁搭配使用,实现同步机制:

pthread_cond_init(&cond,NULL); //初始化条件变量

使用前需要上锁:

pthread_mutex_lock(&lock); //上锁

//判断条件

pthread_cond_wait(&cond, &lock); //阻塞等待条件产生,没有条件产生时阻塞,同时解锁;当条件产生时结束阻塞,再次上锁

//执行任务

pthread_mutex_unlock(&lock); //解锁

pthread_cond_signal(&cond); //产生条件,不阻塞

pthread_cond_destroy(&cond); //销毁条件变量

注意: 必须保证让pthread_cond_wait先执行,pthread_cond_signal再产生条件

练习:打印和转置数组实现同步

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

int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
pthread_mutex_t lock;
pthread_cond_t cond;//初始化条件变量
void *headler_swap(void *arg)
{
    while (1)
    {
        pthread_mutex_lock(&lock);//上锁:申请锁
        //阻塞等待条件产生,没有条件产生时解锁并阻塞
        //当条件产生时结束阻塞,再次上锁
        pthread_cond_wait(&cond,&lock);
        for (int i = 0; i < 5; i++)
        {
            int t = arr[i];
            arr[i] = arr[9 - i];
            arr[9 - i] = t;
        }
        pthread_mutex_unlock(&lock);//解锁:释放锁
    }
    return NULL;
}
void *headler_print(void *arg)
{
    while (1)
    {
        sleep(1);
        pthread_mutex_lock(&lock);//上锁:申请锁
        for (int i = 0; i < 10; i++)
        {
            printf("%d ", arr[i]);
        }
        printf("\n");
        pthread_cond_signal(&cond);//产生条件
        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 error");
        return -1;
    }

    if (pthread_create(&tid1, NULL, headler_swap, NULL) != 0)
    {
        perror("pthread error");
        return -1;
    }

    if (pthread_create(&tid2, NULL, headler_printf, NULL) != 0)
    {
        perror("pthread error");
        return -1;
    }

    pthread_join(tid1, NULL);//为了让整个进程不要结束
    pthread_join(tid2, NULL);
    return 0;
}
  • 13
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值