Linux高并发服务器开发(三)Linux多线程开发

3.1 线程概述

3.1.1 线程概述

        与进程(process)类似,线程(thread)是允许应用程序并发执行多个任务的一种机制。一个进程可以包含多个线程。同一程序中的所有线程均会独立执行相同程序,且共享同一份全局内存区域,其中包括初始化数据段、未初始化数据段以及堆内存段。(传统意义上的 UNIX 进程只是多线程程序的一个特例,该进程只包含一个线程)

        进程是 CPU 分配资源的最小单元,线程是操作系统调度执行的最小单元。

        线程是轻量级的进程(LWP - Light Weight Process),在 Linux 环境下线程的本质仍是进程。

        查看指定进程的 LWP 号:ps -Lf pid

3.1.2 线程和进程的区别

        进程间的信息难以共享。由于除去只读代码段外,父子进程并未共享内存,因此必须采用一些进程间的通信方式,在进程间进行信息交换。

        调用 fork() 来创建进程的代价相对较高,即便利用写时复制技术,仍然需要复制诸如内存页表和文件描述符表之类的多种进程属性,这意味着 fork() 调用在时间上的开销依然不菲。

        线程之间能够方便、快速地共享信息。只需要将数据复制到共享(全局或堆)变量中即可。

        创建线程比创建进程通常要快10倍甚至更多。线程间是共享虚拟地址空间的,无需采用写时复制来复制内存,也无需复制页表。

3.1.3 线程之间共享和非共享资源

        内核区的数据都是共享的;

3.1.4 NPTL(了解) 

        当 Linux 最初开发时,在内核中并不能真正支持线程。但是它的确可以通过 clone() 系统调用将进程作为可调度的实体。这个调用创建了调用进程(calling process)的一个拷贝,这个拷贝与调用进程共享相同的地址空间。LinuxThreads 项目使用这个调用来完全在用户空间模拟对线程的支持。不幸的是这种方法有一些缺点,尤其是在信号处理、调度和进程间同步等方面都存在问题。另外,这个线程模型也不符合 POSIX 的要求。

        要改进 LinuxThreads 需要内核的支持,并且重写线程库。有两个相互竞争的项目开始来满足这些要求。一个包括 IBM 的开发人员的团队开展了 NGPT(Next-Generation POSIX Thread)项目。同时,Red Hat 的一些开发人员开展了 NPTL 项目。NGPT 在2003年中期被放弃,把这个领域完全留给了 NPTL。

        NPTL,或称为 Native POSIX Thread Library,是 Linux 线程的一个新实现,它克服了 LinuxThread 的缺点,同时也符合 POSIX 的需求。与 LinuxTreads 相比,它的性能和稳定性方面都提供了重大的改进。

        查看当前 pthread 库版本:getconf GNU_LIBPTHREAD_VERSION

3.2 创建线程

3.2.1 线程操作相关函数

pthread_t pthread_self(void);

        功能:获取当前的线程的线程id

int pthread_equal(pthread_t t1, pthread_t t2);

        功能:比较两个线程ID是否相等

                (不同的操作系统,pthread_t 类型的实现不一样,有的是无符号的长整形,有的是使用结构体去实现的。通过该函数可以比较两个线程id是否相等)

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); 返回类型是字符串(字符类型指针)

void pthread_exit(void *retval);

        功能:终止一个线程(在哪个线程中调用就是终止哪个线程)

        参数

                retval -- 需要传递一个指针,作为返回值,可以在pthread_join()这个函数中获取它

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

        功能:和一个已经终止的线程进行连接 -- 回收子线程资源

                特点:①该函数是阻塞函数;②调用一次只能回收一个子进程;③一般在主线程中使用

        参数:

                thread -- 需要回收的子线程的ID

                retval -- 接收子进程退出时的返回值

        返回值:

                成功 -- 0

                失败 -- 返回错误号

int pthread_detach(pthread_t thread);

        功能:分离一个线程

                被分离的线程在终止的时候,会自动释放资源返回给系统。

                tips1 不能多次分离,会产生不可预测的行为。

                tips2 不能去连接一个已经分离的线程,会报错。

        参数:

                thread -- 需要分离的线程id

        返回值:

                成功 -- 0

                失败 -- 返回错误号

int pthread_cancel(pthread_t thread);

        功能:取消线程(让线程终止)

                取消某个线程,可以终止该线程的运行。但是不是立刻终止,而是当子线程执行到一个取消点,线程才会终止。

                取消点:系统规定好的一些系统调用,可以粗略的理解为用户区到内核区的切换,这个位置称为取消点

        参数:

                thread -- 

        返回值:

                成功 -- 0

                失败 -- 返回错误号

3.2.2 创建一个线程 

// 一般情况下,main函数所在的线程我们称之为主线程(main线程),其余创建的线程称为子线程
// 程序中默认只有一个进程,fork()函数调用,会有2个进程
// 程序中默认只有一个线程,pthread_create()函数调用,会有2个线程
#include <pthread.h>
#include <stdio.h>
#include <string.h>

void * callback(void * arg) {
    printf("child thread...\n");
    return 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);
    }

    //sleep(1);

    return 0;
}

 若编译的时候直接用(红)是不能编译通过的:因为线程不是标准系统库,是第三方库。所以需要用 -l 去指定库的名称。用 -pthread 编译链接,等同于 -lpthread (绿)。

 该线程不会执行子线程中的代码,只会执行主线程(main线程)中的代码。因为主线程抢占了CPU资源,导致更快到达return 0结束线程。

解决办法:在return 0; 之前睡眠1s -- sleep(1);  // 不是最优解,可用3.3终止进程函数

---------------------------------------------------------------------------------------------------------------------------------将代码改进为pthread_create()函数的第4个参数也传递参数进来的情况:

#include <pthread.h>
#include <stdio.h>
#include <string.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;
}

3.3 终止线程

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

void * callback() {
    printf("child thread id : %d\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("error: %d\n", errstr);
    }

    //主线程
    for(int i = 0; i < 5; i++) {
        printf("%d\n", i);
    }

    printf("tid : %ld, main thread id : %d\n", tid, pthread_self());

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

    return 0;
}

主线程与子线程是交替进行的。当运行 pthread_exit(NULL); 后,线程会结束,之后的代码就不会再执行(在此案例中,主线程不会执行到 return 0; 那一步,子线程就不会受影响)

3.4 连接已终止的线程

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

int value = 10; // 做全局变量

void * callback() {
    printf("child thread id : %d\n", pthread_self());
    // sleep(3); //只有子进程未结束,pthread_join()就不会执行
    // return NULL;

    /*************************************************************/
    // int value = 10; // 局部变量,如果返回这个,那之后主线程打印的*thread_retval将为随机(局部变量的栈空间在线程结束时会被释放)
    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: %d\n", errstr);
    }

    // 主线程
    for(int i = 0; i < 5; i++) {
        printf("%d\n", i);
    }

    printf("tid : %ld, main thread id : %d\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: %d\n", errstr);
    }

    printf("exit data : %d\n", *thread_retval);

    printf("回收子进程资源成功\n");

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

    return 0;
}

为什么要传递二级指针?

        因为我们想在函数内改变一级指针的内容,所以得对它再取地址

3.5 线程的分离

#include <pthread.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("error :%s\n", errstr);
    }

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

    // 设置子线程分离,子线程分离后,子线程结束时对应的资源就不需要主线程去释放了
    pthread_detach(tid);

    // 若设置分离后,对分离的子线程进行连接 pthread_join()
    // 则会产生非法参数

    pthread_exit(NULL); // 退出主线程

    return 0;
}

3.6 线程取消

#include <stdio.h>
#include <pthread.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("error :%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;
}

3.7 线程属性

线程分离后,不需要其他线程对它的资源进行回收,它会自己释放资源

int pthread_attr_init(pthread_attr_t *attr);

        - 初始化线程属性变量

int pthread_attr_destroy(pthread_attr_t *attr);

        - 释放线程属性的资源

int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);

        - 获取线程分离的状态属性

int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);

        - 设置线程分离的状态属性

案例:通过线程属性设置线程分离

#include <stdio.h>
#include <pthread.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, NULL, callback, NULL);
    if(ret != 0) {
        char * errstr = strerror(ret);
        printf("error :%s\n", errstr);
    }

    // 获取线程的栈的大小
    size_t size;
    pthread_attr_getstackstate(&attr, &size);

    printf("thread stack size: %ld\n", size);

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

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

    pthread_exit(NULL); // 退出主线程

    return 0;
}

3.8 线程同步*

3.8.1 案例问题:多线程卖票

        使用多线程实现买票的案例。有三个窗口,一共100张票

//selltickets.c

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

// 所有线程共享这一个资源
int tickets = 100;

void * sellticket(void * arg) {
    
    //买票
    while(tickets > 0) {
        usleep(5000); // 睡眠5000微秒
        printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
        tickets--;
    }

    return NULL;
}

int main() {
    
    // 创建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_detach(tid1);
    pthread_detach(tid2);
    pthread_detach(tid3);
    **************************************/

    // 退出子线程
    pthread_exit(NULL);

    return 0;
}

 此时该程序运行时会产生问题:

产生问题的原因:

        3个线程并发执行抢占CPU资源,所以它们可能获取到同一个tickets,会产生线程安全问题。

3.8.2 线程同步

        线程的主要优势在于,能够通过全局变量来共享信息。不过,这种便捷的共享是有代价的:必须确保多个线程不会同时修改同一变量,或者某一线程不会读取正在由其他线程修改的变量。

        临界区,是指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作,也就是同时访问同一共享资源的其他线程不应中断该片段的执行。

        线程同步,即当有一个线程在对内存进行操作的时候,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处于等待状态。(线程同步会降低并发的效率,但是为了数据安全是必须的)

3.9 互斥锁

3.9.1 互斥量/互斥锁

        为避免线程更新共享变量时出现问题,可以使用互斥量(mutex 是 mutual exclusion 的缩写)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共享资源的原子访问。

        互斥量有两种状态:已锁定(locked)和未锁定(unlocked)。任何时候,至多只有一个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报错失败,具体取决于加锁时使用的方法。

        一旦线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问同一资源时将采用如下协议:

                针对共享资源锁定互斥量

                访问共享资源

                对互斥量解锁

        如果多个线程试图执行这一块代码(一个临界区),事实上只有一个线程能够持有该互斥量(其他线程将遭到阻塞),即同时只有一个线程能够进入这段代码区域:

3.9.2 互斥量相关操作函数

互斥量类型  pthread_mutex_t

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_ *mutex);

        - 加锁,阻塞的(如果有一个线程加锁,其他线程只能阻塞等待)

int pthread_mutex_trylock(pthread_mutex_t *mutex);

        - 尝试加锁,如果加锁失败,不会阻塞,会直接返回

int pthread_mutex_unlock(pthread_mutex_t *mutex);

        - 解锁

3.9.3 案例改进 

        将买票的代码增加互斥锁操作:全局变量增加互斥量、主线程增加互斥量的初始化和释放互斥量、子线程增加上锁/解锁操作。

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

// 所有线程共享这一个资源
int tickets = 100;

// 创建一个互斥量
pthread_mutx_t mutex;

void * sellticket(void * arg) {

    // 加锁
    pthread_mutex_lock(&mutex);
    
    // 买票
    while(tickets > 0) {
        usleep(5000); // 睡眠5000微秒
        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_detach(tid1);
    pthread_detach(tid2);
    pthread_detach(tid3);
    **************************************/
    
    // 退出子线程
    pthread_exit(NULL);

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

    return 0;
}

        该代码还是会有逻辑问题:若A线程上锁后会一直执行while循环直到票为0。

更改:

// 所有线程共享这一个资源
int tickets = 100;

// 创建一个互斥量
pthread_mutx_t mutex;

void * sellticket(void * arg) {

    // 买票
    while(1) {
        // 加锁
        pthread_mutex_lock(&mutex);

        if(tickets > 0) {
            usleep(5000); // 睡眠5000微秒
            printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
            tickets--;
        }else {
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }
     
        // 解锁
        pthread_mutex_unlock(&mutex);
    }

    return NULL;
}

3.10 死锁

        有时,一个线程需要同时访问两个或更多不同的共享资源,而每个资源又都由不同的互斥量管理。当超过一个线程加锁同一组互斥量时,就有可能发生死锁。

        两个或者两个以上的进程在执行过程中,因争夺共享资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁。

        死锁的几种场景:

                忘记释放锁

                重复加锁

                多线程多锁,抢占锁资源

// deadlock.c
// 演示死锁的情况:重复加锁 忘记释放锁


// 所有线程共享这一个资源
int tickets = 100;

// 创建一个互斥量
pthread_mutx_t mutex;

void * sellticket(void * arg) {

    // 买票
    while(1) {
        // 加锁
        pthread_mutex_lock(&mutex);
        // pthread_mutex_lock(&mutex); -- 重复加锁会产生死锁

        if(tickets > 0) {
            usleep(5000); // 睡眠5000微秒
            printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
            tickets--;
        }else {
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }
     
        // 解锁 -- 若忘记释放锁,则会产生死锁的情况
        pthread_mutex_unlock(&mutex);
        // 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_detach(tid1);
    pthread_detach(tid2);
    pthread_detach(tid3);
    **************************************/
    
    // 退出子线程
    pthread_exit(NULL);

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

    return 0;
}
// deadlock1
// 演示死锁的情况:多线程多锁,抢占锁资源

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

// 创建两个互斥量
pthread_mutex_t mutex1, mutex2;


void * workA(void * arg) {

    pthread_mutex_lock(&mutex1);
    sleep(1);
    pthread_mutex_lock(&mutex2);

    printf("workA...\n");

    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);

    return NULL;
}

void * workB(void * arg) {

    pthread_mutex_lock(&mutex2);
    sleep(1);
    pthread_mutex_lock(&mutex1);

    printf("workB...\n");

    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);
    return NULL;
}

int main() {

    // 初始化两个互斥量
    pthread_mutex_init(&mutex1, NULL);
    pthread_mutex_init(&mutex2, NULL);

    // 创建两个子线程
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, workA, NULL);
    pthread_create(&tid2, NULL, workB, NULL);

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

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

    return 0;
}

3.11 读写锁

        当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑到一种情形,当前持有互斥锁的线程只是要读访问共享资源,而同时有其它几个线程也想读取这个共享资源,但是由于互斥锁的排它性,所有其它线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题。

        在对数据的读写操作中,更多的是读数据,写操作比较少,例如对数据库数据的读写应用。为了满足当前能够允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现。

        读写锁的特点:

                如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作。

                如果有其它线程写数据,则其它线程都不允许读、写操作。

                写是独占的,写的优先级高。

3.10.1 读写锁相关操作

读写锁操作类型 pthread_rwlock_t

int pthread_rwlock_init(pthread_ewlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);        // 加读锁

int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);

int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);        // 加写锁

int pthread_rwlock_tyrwrlock(pthread_rwlock_t *rwlock);

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

3.10.2 案例

        创建8个线程,操作同一个全局变量。其中三个线程不定时写该全局变量,五个线程不定时读该全局变量

// rwlock.c

#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(&witd[i], NULL, writeNum, NULL);
    }
    for(int i = 0; i < 5; i++) {
        pthread_create(&ritd[i], NULL, readNum, NULL);
    }

    // 设置线程分离
    for(int i = 0; i < 3; i++) {
        pthread_detach(witd[i]);
    }
    for(int i = 0; i < 5; i++) {
        pthread_detach(ritd[i]);
    }

    pthread_exit(NULL);

    pthread_rwlock_destroy(&rwlock);

    return 0;
}

3.12 生产者和消费者模型

3.12.1 生产者-消费者 模型

3.12.2 写一个简单的 生产者-消费者 模型 

// prodcust.c
/* 
    生产者-消费者 模型  (粗略版)
    运行会有问题(互斥量、信号量解决数据安全问题)
*/

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

// 用一个链表定义容器
struct Node{
    int num;
    struct Node *next;
};

// 头结点
struct Node * head = NULL;

void * producer(void * arg) {

    // 不断的创建新的节点,添加到链表中(使用的头插法)   
    while(1) {

        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());

        usleep(100);
    }
    
    return NULL;
}

void * customer(void * arg) {

    while(1) {
        
        // 保存头结点指针
        struct Node * tmp = head;
        head = head->next;
        printf("delete node, num : %d, tid : %ld\n", tmp->num, pthred_self());
        free(tmp);
        usleep(100);

    }
    
    return NULL;
}

int main() {

    // 创建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]);
    }

    pthread_exit(0);

    return 0;
}

3.13 条件变量

3.13.1 (3.12.2中代码产生的问题)

问题点:

        1. 当有多个线程去操作共享的数据,但是我们没有做数据同步 

        2. 对特殊情况没有做数据处理

         在 customer 回调函数中,有一个头结点指针后移的操作,若 head->next = NULL ,则会出现段错误(消费者没有东西能够消费的情况)

小更改:增加了数据同步,和比较浪费资源的条件

// prodcust.c
/* 
    生产者-消费者 模型  (加锁、加条件变量)
*/

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

// 创建一个互斥量
pthread_mutex_t mutex;

// 用一个链表定义容器
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_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("delete node, num : %d, tid : %ld\n", tmp->num, pthred_self());
            free(tmp);
            // 解锁
            pthread_mutex_unlock(&mutex);
            usleep(100);
        } else {
            // 没有数据
            pthread_mutex_unlock(&mutex);
        }
    }
    
    return NULL;
}

int main() {

    pthread_mutex_init(&mutex, 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_mutex_destroy(&mutex);

    pthread_exit(0);

    return 0;
}

3.13.2 条件变量

条件变量的类型 pthread_cond_t

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);

int pthread_cond_destroy(pthread_cond_t *cond);

int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);

        // 等待(调用该函数,线程会等待/阻塞)

int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);

        // 等待多长时间:调用该函数,线程会阻塞,直到指定的时间结束

int pthread_cond_signal(pthread_cond_t *cond);

        // 通知消费者消费(唤醒一个或者多个)

int pthread_cond_broadcast(pthread_cond_t *cond);

        // 广播,唤醒所有消费者

// prodcust.c
/* 
    生产者-消费者 模型  (加锁、加条件变量)
*/

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

// 创建一个互斥量
pthread_mutex_t mutex;
// 创建一个条件变量
pthread_condi_t cold;

// 用一个链表定义容器
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);

        // 解锁
        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("delete node, num : %d, tid : %ld\n", tmp->num, pthred_self());
            free(tmp);
            // 解锁
            pthread_mutex_unlock(&mutex);
            usleep(100);
        } else {
            // 没有数据,等待
            // 当wait函数调用阻塞时,会对该互斥锁进行解锁,当不阻塞的,继续向下执行,会重新加锁
            pthread_cond_wait(&cond, &mutex);
            pthread_mutex_unlock(&mutex);
        }
        // 或者使用while循环改进需要在if中解锁2次的情况……
        
    }
    
    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_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    pthread_exit(0);

    return 0;
}

3.14 信号量

头文件 #include <semaphore>

信号量的类型 sem_t

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,就阻塞

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);

//semaphore.c
/*
    -- 伪代码 --

    sem_t psem;
    sem_t csem;

    init(psem, 0, 8); // 生产者初始化线程(0)为8 
    init(csem, 0, 0); // 消费者初始化线程(0)为0

    producer() {
        sem_wait(&psem); // 对生产者进行-1
        
        sem_post(&csem); // 对消费者进行+1
    }

    customer() {
        sem_wait(&csem); //对消费者-1 

        sem_post(&psem); //对生产者+1
    }
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore>

// 创建一个互斥量
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) {

        // -1,默认为8
        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);

        // +1,默认为0
        sem_post(&csem);

    }
    
    return NULL;
}

void * customer(void * arg) {

    while(1) {
        
        // -1,为0时无法-1,则阻塞
        sem_wait(&csem);

        // 加锁
        pthread_mutex_lock(&mutex);
    
        // 保存头结点指针
        struct Node * tmp = head;

        head = head->next;
        printf("delete node, num : %d, tid : %ld\n", tmp->num, pthred_self());
        free(tmp);
        // 解锁
        pthread_mutex_unlock(&mutex);

        // +1
        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(0);

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值