第3章Linux多线程开发

线程概述

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

创建线程

在这里插入图片描述

与线程相关的,编译和链接时需要-pthread或者-lpthread
pthread_create

//一般情况下,main函数所在的线程称之为主线程(main线程),其余创建的称之为子线程
//程序中默认只有一个进程,fork()函数调用,2个进程
//程序中默认只有一个线程,pthread_create()函数调用,2个线程
//需要头文件
#include <pthread.h>
//函数原型
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
/*
    功能:创建一个子线程
    参数:
        -thread:传出参数,线程创建成功后,子线程的线程ID写入到该变量中
        -attr:设置线程的属性,一般使用默认值,NULL
        -start_routine:函数指针,这个函数是子线程需要处理的逻辑代码
        -arg:给第三个参数使用,传参
    返回值:
        成功:返回0
        失败:返回错误号,这个错误号和之前的errno不太一样
            获取错误号信息:char* strerror(int errnum);(string.h)
*/

示例

#include<stdio.h>
#include <pthread.h>
#include<string.h>
#include<unistd.h>
void* callback(void* arg)
{
    printf("child thread...\n");
    printf("arg value : %d\n",*(int*)arg);
    return NULL;
}
int main()
{
    //创建一个子线程
    pthread_t tid;
    int num = 10;
    int ret = pthread_create(&tid,NULL,callback,(void*)&num);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error : %s\n",errstr);
    }

    for(int i=0;i<5;i++)
        printf("%d\n",i);
    sleep(1);   //等待一下子线程执行
    return 0;
}

gcc pthread_create.c -o pthread_create -pthread

终止线程

pthread_exit

//需要头文件
#include <pthread.h>
//函数原型
void pthread_exit(void *retval);
/*
    功能:终止一个线程,在哪个线程中调用,就表示终止哪个线程
    参数:
        retval:需要传递一个指针,作为一个返回值,可以在pthread_join()中获取到。
*/
//函数原型
pthread_t pthread_self(void);
/*
    功能:获取当前的线程的线程ID
*/
//函数原型
int pthread_equal(pthread_t t1, pthread_t t2);
/*
    功能:比较两个线程ID是否相等
    不同的操作系统,pthread_t类型的实现不一样,有的是无符号的长整型,有的是使用结构体去实现
*/

示例

#include<stdio.h>
#include <pthread.h>
#include<string.h>
void* callback(void* arg)
{
    printf("child thread id : %ld\n",pthread_self());
    return NULL;    //相当于pthread_exit(NULL);
}
int main()
{
    //创建一个子进程
    pthread_t tid;
    int ret = pthread_create(&tid,NULL,callback,NULL);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error : %s\n",errstr);
    }
    //主线程
    for(int i=0;i<5;i++)
    {
        printf("%d\n",i);
    }
    printf("tid : %ld , main thread id : %ld\n",tid,pthread_self());
    
    //让主线程退出,当主线程退出时,不会影响其他正常运行的线程。
    pthread_exit(NULL);

    return 0;
}

连接已终止的进程

pthread_join

//需要头文件
#include <pthread.h>
//函数原型
int pthread_join(pthread_t thread, void **retval);
/*
    功能:和一个已终止的线程进行连接
        回收子线程的资源
        这个函数是阻塞函数,调用一次只能回收一个子线程
        一般在主线程中使用
    参数:
        -thread:需要回收的子线程的ID
        -retval:接收子线程退出时的返回值
    返回值:
        成功:0
        失败:非0,返回的错误号
*/

示例:

#include<stdio.h>
#include <pthread.h>
#include<string.h>
#include<unistd.h>
int value = 10;
void* callback(void* arg)
{
    printf("child thread id : %ld\n",pthread_self());
    sleep(3);
    //return NULL;    //相当于pthread_exit(NULL);
    pthread_exit((void*)&value); //相当于 return (void*)&value;
}
int main()
{
    //创建一个子进程
    pthread_t tid;
    int ret = pthread_create(&tid,NULL,callback,NULL);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error : %s\n",errstr);
    }
    //主线程
    for(int i=0;i<5;i++)
    {
        printf("%d\n",i);
    }
    printf("tid : %ld , main thread id : %ld\n",tid,pthread_self());
    
    //主线程调用pthread_join()回收子线程的资源
    int* thread_retval;
    ret = pthread_join(tid,(void**)&thread_retval);
    if(ret!=0)
    {
        char* errstr = strerror(ret);
        printf("error : %s\n",errstr);
    }
    printf("exit data : %d\n",*thread_retval);
    printf("回收子线程资源成功!\n");

    //让主线程退出,当主线程退出时,不会影响其他正常运行的线程。
    pthread_exit(NULL);

    return 0;
}

线程的分离

pthread_detach

//需要头文件
#include <pthread.h>
//函数原型
int pthread_detach(pthread_t thread);
/*
    功能:分离一个线程,被分离的线程在终止的时候,会自动释放资源返回给系统
        1.不能多次分离,会产生不可预料的行为
        2.不能去连接(join)一个已经分离的线程,会报错
    参数:需要分离的线程的ID
    返回值:
        成功:0
        失败:错误号
*/

示例:

#include<pthread.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
void* callback(void* arg)
{
    printf("child thread id: %ld\n",pthread_self());
    return NULL;
}
int main()
{
    //创建一个子线程
    pthread_t tid;
    int ret = pthread_create(&tid,NULL,callback,NULL);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error1 : %s\n",errstr);
    }

    //输出主线程和子线程ID
    printf("tid: %ld,main thread id: %ld\n",tid,pthread_self());

    //设置子线程分离,子线程分离后,子线程结束时对应的资源就不需要主线程释放
    ret = pthread_detach(tid);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error2 : %s\n",errstr);
    }

    //设置分离后,对分离的子线程进程连接join
    ret = pthread_join(tid,NULL);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error3 : %s\n",errstr); //输出error3 : Invalid argument
    }

    pthread_exit(NULL);
    return 0;
}

线程取消

pthread_cancel

//需要头文件
#include <pthread.h>
//函数原型
int pthread_cancel(pthread_t thread);
/*
    功能:取消线程(让线程终止)
        取消某个线程,可以终止某个线程的运行
        但不是立刻终止,而是当子线程执行到一个取消点,线程才会终止
        取消点:系统规定好的一些系统调用
            我们可以粗略地理解为从用户区到内核区的切换,这个位置称之为取消点
*/

示例:

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

void* callback(void* arg)
{
    printf("child thread id: %ld\n",pthread_self());
    for(int i=0;i<5;i++)
        printf("child:%d\n",i);
    return NULL;
}
int main()
{
    //创建一个子线程
    pthread_t tid;
    int ret = pthread_create(&tid,NULL,callback,NULL);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error1 : %s\n",errstr);
    }

    //取消线程
    pthread_cancel(tid);
    
    for(int i=0;i<5;i++)
        printf("%d\n",i);
    
    //输出主线程和子线程ID
    printf("tid: %ld,main thread id: %ld\n",tid,pthread_self());

    pthread_exit(NULL);
    return 0;
}

线程属性

在这里插入图片描述

//需要头文件
#include <pthread.h>
//函数原型
int pthread_attr_init(pthread_attr_t *attr);
/*
    功能:初始化线程属性变量
*/
int pthread_attr_destroy(pthread_attr_t *attr);
/*
    功能:释放线程属性的资源
*/
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
/*
    功能:获取线程分离的状态属性
    PTHREAD_CREATE_DETACHED
    PTHREAD_CREATE_JOINABLE(默认)
*/
int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);
/*
    功能:设置线程分离的状态属性
*/

示例:

#include<pthread.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
void* callback(void* arg)
{
    printf("child thread id: %ld\n",pthread_self());
    return NULL;
}
int main()
{
    //创建一个线程属性变量
    pthread_attr_t attr;
    //初始化属性变量
    pthread_attr_init(&attr);
    //设置属性
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

    //创建一个子线程
    pthread_t tid;
    int ret = pthread_create(&tid,&attr,callback,NULL);
    if(ret != 0)
    {
        char* errstr = strerror(ret);
        printf("error1 : %s\n",errstr);
    }
    
    //获取线程栈的大小
    size_t stacksize;
    pthread_attr_getstacksize(&attr,&stacksize);
    printf("thread stack size : %ld\n",stacksize);

    //输出主线程和子线程ID
    printf("tid: %ld,main thread id: %ld\n",tid,pthread_self());

    //释放线程属性资源
    pthread_attr_destroy(&attr);

    pthread_exit(NULL);
    return 0;
}

线程同步

在这里插入图片描述

互斥锁

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

#include<pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
/*
    功能:初始化互斥量
    参数:
        -mutex:需要初始化的互斥量变量
        -attr:互斥量相关的属性,NULL(使用默认的)
    restrict:C语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作
*/
int pthread_mutex_destroy(pthread_mutex_t *mutex);
/*
    释放互斥量的资源
*/
int pthread_mutex_lock(pthread_mutex_t *mutex);
/*
    加锁,阻塞的(如果有一个线程加锁了,那么其他的线程只能阻塞等待)
*/
int pthread_mutex_trylock(pthread_mutex_t *mutex);
/*
    尝试加锁,如果加锁失败,不会阻塞,会直接返回
*/
int pthread_mutex_unlock(pthread_mutex_t *mutex);
/*
    解锁
*/

示例:

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
//全局变量,共享资源
int tickets = 1000;
//创建互斥量
pthread_mutex_t mutex;
void* sellticket(void* arg)
{
    //卖票
    while(1)
    {
        //加锁
        pthread_mutex_lock(&mutex);

        if(tickets>0)
        {
            usleep(6000);
            printf("%ld 正在卖第 %d 张门票\n",pthread_self(),tickets);
            tickets--;
        }
        
        //解锁
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main()
{
    //初始化互斥量
    pthread_mutex_init(&mutex,NULL);

    //创建3个子线程
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,NULL,sellticket,NULL);
    pthread_create(&tid2,NULL,sellticket,NULL);
    pthread_create(&tid3,NULL,sellticket,NULL);

    //回收子线程的资源,阻塞
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);

    //释放互斥量资源
    pthread_mutex_destroy(&mutex);

    pthread_exit(NULL);//退出主线程
    return 0;
}

死锁

在这里插入图片描述

读写锁

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

//读写锁类型 pthread_rwlock_t
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwptr);
int pthread_rwlock_rdlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_unlock(pthread_rwlock_t *rwptr);

示例:

//创建8个线程,操作同一个全局变量
//3个线程不定时写全局变量,5个线程不定时读全局变量
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>

//创建一个共享数据
int num=1;
pthread_rwlock_t rwlock;
void* writeNum(void* arg)
{
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock);
        num++;
        printf("++write, tid : %ld, num : %d\n",pthread_self(),num);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
    return NULL;
}
void* readNum(void* arg)
{
    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("==read, tid : %ld, num : %d\n",pthread_self(),num);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
    return NULL;
}
int main()
{
    pthread_rwlock_init(&rwlock,NULL);
    //创建3个写线程,5个读线程
    pthread_t wtids[3],rtids[5];
    for(int i=0;i<3;i++)
        pthread_create(&wtids[i],NULL,writeNum,NULL);

    for(int i=0;i<5;i++)
        pthread_create(&rtids[i],NULL,readNum,NULL);

    //设置线程分离
    for(int i=0;i<3;i++)
        pthread_detach(wtids[i]);
        
    for(int i=0;i<5;i++)
        pthread_detach(rtids[i]);

    pthread_exit(NULL);
    pthread_rwlock_destroy(&rwlock);
    return 0;
}

生产者和消费者模型

在这里插入图片描述

条件变量

在这里插入图片描述
示例:

//生产者消费者模型(粗略条件变量版本)
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
//创建一个互斥量
pthread_mutex_t mutex;
//创建条件变量
pthread_cond_t cond;
struct Node
{
    int num;
    struct Node* next;
};
//头结点
struct Node* head=NULL;
void* producer(void* arg)
{
    //不断创建新节点,添加到链表中
    while(1)
    {
        pthread_mutex_lock(&mutex);
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode->next = head;
        head = newNode;
        newNode->num=rand()%1000;
        printf("add node, num: %d , tid: %ld\n",newNode->num,pthread_self());
        
        //只要生成一个,就通知消费者消费
        pthread_cond_signal(&cond);
        //signal通知一个或多个,broadcast广播全部通知
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }
    return NULL;
}
void* customer(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        struct Node* tmp = head;
        if(head != NULL)
        {
            head=head->next;
            printf("del node, num: %d , tid: %ld\n",tmp->num,pthread_self());
            free(tmp);
            pthread_mutex_unlock(&mutex);
            usleep(100);
        }
        else
        {
            //没有数据,需要等待
            //当这个函数调用阻塞的时候,会先对互斥锁进行解锁,在解除阻塞时,会再加上锁
            pthread_cond_wait(&cond,&mutex);
            //当生产者生产,通知了,就解除阻塞
            pthread_mutex_unlock(&mutex);
        }
    }
    return NULL;
}
int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);

    //创建5个生成者,5个消费者
    pthread_t ptids[5],ctids[5];
    for(int i=0;i<5;i++)
    {
        pthread_create(&ptids[i],NULL,producer,NULL);
        pthread_create(&ctids[i],NULL,customer,NULL);
    }

    //线程分离
    for(int i=0;i<5;i++)
    {
        pthread_detach(ptids[i]);
        pthread_detach(ctids[i]);
    }

    while(1)
        sleep(10);

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
    pthread_exit(NULL);
    return 0;
}

信号量

在这里插入图片描述

#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
/*
    初始化信号量
    参数:
        -sem:信号量变量的地址
        -pshared:
            -0:用在线程间
            -非0:用在进程间
        -value:信号量中的值
*/
int sem_destroy(sem_t *sem);
/*
    释放资源
*/
int sem_wait(sem_t *sem);
/*
    对信号量的值-1,如果值为0,就阻塞至大于0
*/
int sem_trywait(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
int sem_post(sem_t *sem);
/*
    对信号量解锁,调用一次,对信号量的值+1
*/
int sem_getvalue(sem_t *sem, int *sval);

示例:

//生产者消费者模型(信号量版本)
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<semaphore.h>
//创建一个互斥量
pthread_mutex_t mutex;
//创建两个信号量
sem_t psem;
sem_t csem;

struct Node
{
    int num;
    struct Node* next;
};
//头结点
struct Node* head=NULL;
void* producer(void* arg)
{
    //不断创建新节点,添加到链表中
    while(1)
    {
        sem_wait(&psem);

        pthread_mutex_lock(&mutex);
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
        newNode->next = head;
        head = newNode;
        newNode->num=rand()%1000;
        printf("add node, num: %d , tid: %ld\n",newNode->num,pthread_self());
        pthread_mutex_unlock(&mutex);

        sem_post(&csem);
    }
    return NULL;
}
void* customer(void* arg)
{
    while(1)
    {
        sem_wait(&csem);

        pthread_mutex_lock(&mutex);
        struct Node* tmp = head;
        head=head->next;
        printf("del node, num: %d , tid: %ld\n",tmp->num,pthread_self());
        free(tmp);
        pthread_mutex_unlock(&mutex);
        
        sem_post(&psem);
    }
    return NULL;
}
int main()
{
    pthread_mutex_init(&mutex,NULL);
    sem_init(&psem,0,8);
    sem_init(&csem,0,0);

    //创建5个生成者,5个消费者
    pthread_t ptids[5],ctids[5];
    for(int i=0;i<5;i++)
    {
        pthread_create(&ptids[i],NULL,producer,NULL);
        pthread_create(&ctids[i],NULL,customer,NULL);
    }

    //线程分离
    for(int i=0;i<5;i++)
    {
        pthread_detach(ptids[i]);
        pthread_detach(ctids[i]);
    }

    while(1)
        sleep(10);

    pthread_mutex_destroy(&mutex);
    pthread_exit(NULL);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值