线程啊线程

线程

概念

轻量级的进程,为了提高系统的性能 而引入了线程。线程和进程都参与统一的调度。

进程与线程的区别

共同点:

都为操作系统提供了并发执行能力,都参与统一调度。

不同点:

调度和资源方面:线程是系统调度的最小单位,进程是资源分配的最小单位。
地址空间方面:同一个进程创建的多个线程共享进程的资源;进程的地址空间相互独立。
通信方面:线程通信相对简单,只需要通过全局变量可以实现,但是需要考虑临界资源访问的问题;
进程通信比较复杂,需要借助进程间的通信机制(借助3g-4g内核空间)。
安全性方面:线程安全性差一些,当进程结束时会导致所有线程退出;进程相对安全。

线程资源

共享的资源:

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

私有的资源:

线程ID (TID)、PC(程序计数器)和相关寄存器、堆栈、错误号 (errno)、信号掩码和优先级、执行状态和属性

函数接口

创建线程( pthread_create )

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 
                    void *(*start_routine) (void *), void *arg);
功能:创建线程
参数:thread:线程标识
            attr:线程属性, NULL:代表设置默认属性
            start_routine:函数名:代表线程函数
            arg:用来给前面函数传参
返回值: 成功:0
        失败:错误码

在这里插入图片描述
以下代码 有两种可能情况:
在这里插入图片描述

回收线程( pthread_join / detach)

int  pthread_join(pthread_t thread,  void **value_ptr); 

功能:用于等待一个指定的线程结束,阻塞函数
参数:thread:创建的线程对象
        value_ptr:指针*value_ptr指向线程返回的参数
返回值:成功: 0
       失败:errno
int pthread_detach(pthread_t thread);

功能:子线程退出,自动回收资源,不阻塞
参数:thread:创建的线程对象
返回值:成功: 0
       失败:errno

退出线程( pthread_exit )

int  pthread_exit(void *value_ptr); 

功能:用于退出线程的执行
参数:value_ptr:线程退出时返回的值(任意类型)
返回值: 成功 : 0
    	失败:errno

在这里插入图片描述
以上代码中 “end” 一定在最后输出。

练习:通过线程实现数据的交互

主线程循环从终端输入,线程函数将数据循环输出,当输入 “quit” 结束程序。

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

char buffer[64];
int flag = 0;

void *handler(void *arg){
    
    while (1){
        if (flag != 0){
            if (!strcmp(buffer, "quit"))
                break; 
            printf("%s\n", buffer);
            flag = 0;
        }
    }

    pthread_exit(0);
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL)){
        perror("Failed: ");
        return -1;
    }

    while (1){
        scanf("%s", buffer);
        // scanf有阻塞机制,不需要判断flag==0,线程函数一定能抢到时间片
        // fgets也有阻塞
        flag = 1; 
        if (!strcmp(buffer, "quit"))
            break;  
    }    

    pthread_join(tid, NULL);

    return 0;
}

在这里插入图片描述
在这里插入图片描述

同步

同步(synchronization)指的是多个任务(线程)按照约定的顺序相互配合完成一件事情。

同步机制

1、信号量

通过信号量实现同步操作;由信号量来决定线程继续运行还是阻塞等待。
信号量代表某一类资源,其值表示系统中该资源的数量:
信号量值 > 0,表示有资源可以用,可以申请到资源,继续执行程序;
信号量值<=0,表示没有资源可以用,无法申请到资源,阻塞。
信号量是一个受保护的变量,只能通过三种操作来访问:
初始化 sem_init、P操作(申请资源)sem_wait、V操作(释放资源)sem_post

函数( sem_init、sem_wait、sem_post )
int  sem_init(sem_t *sem,  int pshared,  unsigned int value);  

功能:初始化信号量   
参数:sem:初始化的信号量对象
    pshared:信号量共享的范围(0: 线程间使用   非0:1进程间使用)
    value:信号量初值
返回值:成功 0
       失败 -1
int  sem_wait(sem_t *sem); 

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

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

在这里插入图片描述

练习:通过信号量实现线程间同步

主线程循环从终端输入,线程函数将数据循环输出,当输入 “quit” 结束程序。

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

char buffer[64];
sem_t sem;

void *handler(void *arg){
    
    while (1){
        sem_wait(&sem);						// 若线程一直阻塞,程序不能退出
        if (!strcmp(buffer, "quit"))
            exit(0);
        printf("%s\n", buffer);  
    }
    pthread_exit(0);
}

int main(int argc, char const *argv[])
{
    sem_init(&sem, 0, 0);					// 若不 post,则将不能结束 wait,线程阻塞
	pthread_t tid;
    if (pthread_create(&tid, NULL, handler, NULL)){
        perror("Failed: ");
        return -1;
    }

    while (1){
        scanf("%s", buffer);
        // fgets(buffer, 64, stdin);
        // if (buffer[strlen(buffer)-1] == '\n')
        //     buffer[strlen(buffer)-1] = '\0';

        if (!strcmp(buffer, "quit"))		
            exit(0); 			// 如果用 break; 将此 if 放到 post 后才行,不然下一句不执行
        sem_post(&sem);		
    }    

    pthread_join(tid, NULL);

    return 0;
}

在这里插入图片描述

练习:开启两个线程分别打印A、B,每个线程打印10遍

要求输出必须按照AB的顺序显示,即:ABABAB…

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

char buffer[64];
sem_t sem1, sem2;

void *print1(void *arg){

    for (int i = 1; i < 11; i++){
        sem_wait(&sem1);
        printf("%d: A\t", i);        
        sem_post(&sem2);
    }
    pthread_exit(0);
}

void *print2(void *arg){

    for (int i = 1; i < 11; i++){
        sem_wait(&sem2);
        printf("%d: B\t", i);        
        sem_post(&sem1);
    }
    putchar(10);
    pthread_exit(0);
}

int main(int argc, char const *argv[])
{
    sem_init(&sem1, 0, 1);
    sem_init(&sem2, 0, 0);

    pthread_t tid1, tid2;
    if (pthread_create(&tid1, NULL, print1, NULL)){
        perror("Failed: ");
        return -1;
    }
    if (pthread_create(&tid2, NULL, print2, NULL)){
        perror("Failed: ");
        return -1;
    }

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}

运行结果如下:
在这里插入图片描述

2、互斥锁 + 条件变量

如下“条件变量”。

互斥

临界资源: 一次仅允许一个进程/线程所使用的资源
临界区: 指的是一个访问共享资源的程序片段

概念

多个线程在访问某临界资源时,同一时间只能一个线程进行访问。

信号量也可实现线程间互斥

多个线程抢夺同一信号量即可。

互斥锁:

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

函数

pthread_mutex_init
int  pthread_mutex_init(pthread_mutex_t  *mutex, pthread_mutexattr_t *attr);  

功能:初始化互斥锁  
参数:mutex:互斥锁
    attr:  互斥锁属性  		// NULL表示缺省属性
返回值:成功 0
       失败 -1
pthread_mutex_lock
int  pthread_mutex_lock(pthread_mutex_t *mutex); 

功能:申请互斥锁     
参数:mutex:互斥锁
返回值:成功 0
      失败 -1

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

pthread_mutex_unlock
int  pthread_mutex_unlock(pthread_mutex_t *mutex); 

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

功能:销毁互斥锁     
参数:mutex:互斥锁
练习:两个线程实现数组倒置(part1)

线程一用于循环倒置,线程二用于循环打印(延时)。

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

char arr[10] = {};
pthread_mutex_t lock;
char temp;

void *ver(void *arg){

    while (1){
        pthread_mutex_lock(&lock);
        for (int i = 0 ; i < 5; i++){
            temp = arr[i];
            arr[i] = arr[9-i];
            arr[9-i] = temp; 
        }
        pthread_mutex_unlock(&lock);
    }
    pthread_exit(0);
}

void *print(void *arg){

    while (1){
        pthread_mutex_lock(&lock);
        for (int i = 0; i < 10; i++)
            printf("%c\t", arr[i]);
        pthread_mutex_unlock(&lock);
        putchar(10);
        sleep(2);
    }
    pthread_exit(0);
}

int main(int argc, char const *argv[])
{
    for (int i = 0; i < 10; i++)
        arr[i] = i + 48;
    for (int i = 0; i < 10; i++)
        printf("%c\t", arr[i]);
    printf("\n*************\n");
    
    pthread_mutex_init(&lock, NULL);

    pthread_t tid1, tid2;
    if (pthread_create(&tid1, NULL, ver, NULL)){
        perror("Failed: ");
        return -1;
    }
    if (pthread_create(&tid2, NULL, print, NULL)){
        perror("Failed: ");
        return -1;
    }

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_mutex_destroy(&lock);

    return 0;
}

在这里插入图片描述

实现效果如下:
在这里插入图片描述

条件变量

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

功能:等待信号的产生
参数:restrict cond:要等待的条件
     restrict mutex:对应的锁
返回值:成功:0,失败:非0
注:当没有条件产生时函数会阻塞,同时会将锁解开;如果等待到条件产生,函数会结束阻塞同时进行上锁。
pthread_cond_signal
int pthread_cond_signal(pthread_cond_t *cond);

功能:给条件变量发送信号
参数:cond:条件变量值
返回值:成功:0,失败:非0
注:必须等待 pthread_cond_wait 函数先执行,再产生条件才可以。
pthread_cond_destroy
int pthread_cond_destroy(pthread_cond_t *cond);

功能:将条件变量销毁
参数:cond:条件变量值
返回值:成功:0, 失败:非0
步骤
1)pthread_cond_init(&cond, NULL):初始化
2)pthread_mutex_lock(&lock); // 上锁
pthread_cond_wait(&cond, &lock);

// 阻塞 等待条件产生:没有条件产生时阻塞,同时解锁;当条件产生时结束阻塞,再次上锁

3)pthread_cond_signal(&cond):产生条件,不阻塞

须保证:pthread_cond_wait 先执行,pthread_cond_signal 再产生条件

练习:两个线程实现数组倒置(part2)

线程一用于循环倒置,线程二用于循环打印(延时)。

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

char arr[10] = {};
pthread_mutex_t lock;
char temp;
pthread_cond_t condition;

void *ver(void *arg){

    while (1){
        sleep(2);						// 使另外一个线程先拿到锁
        pthread_mutex_lock(&lock);
        for (int i = 0 ; i < 5; i++){
            temp = arr[i];
            arr[i] = arr[9-i];
            arr[9-i] = temp; 
        }
        pthread_cond_signal(&condition);			// 发送条件
        pthread_mutex_unlock(&lock);
    }
    pthread_exit(0);
}

void *print(void *arg){

    while (1){
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&condition, &lock);		// 第一次:没条件,解锁并等待
        for (int i = 0; i < 10; i++)				// 第二次:有条件,继续执行并上锁
            printf("%c\t", arr[i]);
        pthread_mutex_unlock(&lock);
        putchar(10);
    }
    pthread_exit(0);
}

int main(int argc, char const *argv[])
{
    for (int i = 0; i < 10; i++)
        arr[i] = i + 48;
    for (int i = 0; i < 10; i++)
        printf("%c\t", arr[i]);
    printf("\n*************\n");
    
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&condition, NULL);

    pthread_t tid1, tid2;
    if (pthread_create(&tid1, NULL, ver, NULL)){
        perror("Failed: ");
        return -1;
    }
    if (pthread_create(&tid2, NULL, print, NULL)){
        perror("Failed: ");
        return -1;
    }

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&condition);

    return 0;
}

在这里插入图片描述

实现效果如下:
在这里插入图片描述

练习:两个线程实现字符串循环倒序输出
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

int flag = 0;
char buf[64] = "";
pthread_mutex_t lock;
pthread_cond_t condition;

void *reverse(void *arg){
    while (1){
        char *p = buf;
        char *head = p;
        char *tail = NULL;
        while (*(p+1) != '\0')
            p++;
        tail = p;

        sleep(2);
        pthread_mutex_lock(&lock);
        
        while (head < tail){
            *head ^= *tail;
            *tail ^= *head;
            *head++ ^= *tail--;
        }

        pthread_cond_signal(&condition);			// 
        pthread_mutex_unlock(&lock);
    }
    pthread_exit(0);
}

void *output(void *arg){

    while (1){
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&condition, &lock);

        printf("%s\n", buf);

        pthread_mutex_unlock(&lock);
    }
    pthread_exit(0);
}

int main(int argc, char const *argv[])
{
    strcpy(buf, "Welcome to my world!");

    pthread_t tid1, tid2;
    if (pthread_create(&tid1, NULL, output, NULL) != 0){
        perror("Failed to create a thread");
        return -1;
    }
    if (pthread_create(&tid2, NULL, reverse, NULL) != 0){
        perror("Failed to create a thread");
        return -1;
    }
  
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&condition);
    return 0;
}

死锁

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

产生的四个必要条件

1、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用;
2、不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放;
3、请求和保持,即当资源请求者在请求其他的资源的同时,保持对原有资源的占有;
4、循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。
注意: 当上述四个条件都成立的时候,便形成死锁。
当然,死锁的情况下如果打破上述任何一个条件,便可让死锁消失。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值