Linux多线程开发

一、线程

1、线程概述

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

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

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

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

2、线程和进程区别

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

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

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

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

3、线程和进程虚拟地址空间

在这里插入图片描述

4、线程之间共享和非共享资源

共享资源

进程 ID 和父进程 ID
进程组 ID 和会话 ID
用户 ID 和 用户组 ID
文件描述符表
信号处置
文件系统的相关信息:文件权限掩码(umask)、当前工作目录
虚拟地址空间(除栈、 .text)

非共享资源

线程 ID
信号掩码
线程特有数据
error 变量
实时调度策略和优先级
栈,本地变量和函数的调用链接信息

5、NPTL

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

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

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

查看当前 pthread 库版本: getconf GNU_LIBPTHREAD_VERSION

qykhhr@qykhhr:~$ getconf GNU_LIBPTHREAD_VERSION
NPTL 2.27

6、线程操作

一般情况下,main 函数所在的线程我们称之为主线程(main线程),其余创建的线程称为子线程。
程序中默认只有一个进程,fork()函数调用,会产生一个子进程,总共有2个进程。
程序中默认只有一个线程,pthread_create()调用,会产生一个子线程,总共有2个线程。

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

#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不一样
获取错误号信息:strerror(int errnum); 不能通过perrno()打印函数信息

/*
一般情况下,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不一样
            获取错误号信息:strerror(int errnum); 不能通过perrno()打印函数信息
*/
#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);
    
    *(int *)arg += 10;
    
   	printf("arg += 10, value:%d\n",*(int *)arg);
    
    return NULL;
}
int main()
{
    // 创建一个子进程
    pthread_t tid;
    // 子线程只会执行 callback 回调函数中的代码
    // int ret = pthread_create(&tid,NULL,callback,NULL);
    int num = 10;
    int ret = pthread_create(&tid,NULL,callback,(void *)&num);
    if(ret != 0)
    {
        char * errstr = strerror(ret);
        printf("error:%s\n",errstr);
        return -1;
    }
    // 确保子线程抢到CPU
    sleep(1);
    for(int i = 0; i < 5; i++)
    {
        printf("%d\n",i);
    }
    printf("num value:%d\n",num);
    return 0;
}

注意,汇编时需要指定静态库,gcc -o xxx xxx.c -pthread(-lpthread或-l pthread)

qykhhr@qykhhr:~/Linux/lesson29$ gcc -o pthread_create pthread_create.c -l pthread
qykhhr@qykhhr:~/Linux/lesson29$ ./pthread_create 
child thread...
arg value:10
arg += 10, value:20
0
1
2
3
4
num value:20

void pthread_exit(void *retval);

#include <pthread.h>
void pthread_exit(void *retval);
Compile and link with -pthread.
功能:终止一个线程,在哪个线程中调用,就表示终止哪个线程
参数:
retval:需要传递一个指针,作为一个返回值,可以在 pthread_join() 中获取到

/*
#include <pthread.h>
void pthread_exit(void *retval);
Compile and link with -pthread.
    功能:终止一个线程,在哪个线程中调用,就表示终止哪个线程
    参数:
        retval:需要传递一个指针,作为一个返回值,可以在 pthread_join() 中获取到

#include <pthread.h>
pthread_t pthread_self(void);
Compile and link with -pthread.
    功能:获取调用线程的ID

#include <pthread.h>
int pthread_equal(pthread_t t1, pthread_t t2);
    功能;比较两个线程ID是否相等
        不同的操作系统,pthread_t 类型的实现不一样,有的是无符号的长整型,有的是使用结构体去实现的
        
*/

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

void * callback(void * args)
{
    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 * str = strerror(ret);
        printf("error:%s\n",str);
        return -1;
    }
    // 开发中不要使用sleep,使用pthread_exit(NULL),不会影响其他正在运行的线程。
    // sleep(1);
    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),不会影响其他正在运行的线程。
    pthread_exit(NULL);
    // main 线程退出后,下面的代码都会再执行
    printf("main thread end...\n");
    return 0;
}
qykhhr@qykhhr:~/Linux/lesson29$ gcc -o pthread_exit pthread_exit.c -pthread
qykhhr@qykhhr:~/Linux/lesson29$ ./pthread_exit 
0
1
2
3
4
tid:140022763325184, main thread id:140022771840832
child thread ID = 140022763325184

pthread_t pthread_self(void);

#include <pthread.h>
pthread_t pthread_self(void);
Compile and link with -pthread.
功能:获取调用线程的ID

int pthread_equal(pthread_t t1, pthread_t t2);

#include <pthread.h>
int pthread_equal(pthread_t t1, pthread_t t2);
功能;比较两个线程ID是否相等

不同的操作系统,pthread_t 类型的实现不一样,有的是无符号的长整型,有的是使用结构体去实现的,所以我们不能直接使用 == 符号来判断两个线程的类型是否相同,而要调用pthread_equal方法来判断。

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

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

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

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

int num = 10;
void * callback(void * args)
{
    printf("child thread ID = %ld\n",pthread_self());
    sleep(3);
    // return NULL; // 相当于 pthread_exit(NULL);
    // int num = 10; // 不要返回局部变量,返回局部变量会随着函数调用后销毁,再次使用指针访问就会出现数据不一致
    // 可以返回全局变量
    pthread_exit((void *)&num);
}
int main()
{
    // 创建一个子线程
    pthread_t tid;
    int ret = pthread_create(&tid,NULL,callback,NULL);
    if(ret != 0)
    {
        char * str = strerror(ret);
        printf("error:%s\n",str);
        return -1;
    }
    // 开发中不要使用sleep,使用pthread_exit(NULL),不会影响其他正在运行的线程。
    // sleep(1);
    for(int i = 0; i < 5; i++)
    {
        printf("%d\n",i);
    }
    printf("tld:%ld, main thread id:%ld\n",tid,pthread_self());

    // 主线程中调用 pthread_join() 回收子线程的资源
    // ret = pthread_join(tid,NULL);
    int * thread_retval;
    // 为什么要用二级指针,因为返回返回的就是一级指针我们要想修改只能是传入二级指针。原理同:定义一个全局变量,我们要修改这个值,需要传入这个全局变量的地址才行
    // 函数callback返回的是一个指针,要想接收这个返回值需要一个指针类型。    所以定义了 int *thread_retval去接收返回的指针。
    // 但是如果直接将 thread_retval传入函数pthread_join,它就是一个局部参数,当结束函数pthread_join回到主线程,thread_retval的值是不会改变的。这样起不到用thread_retval接收返回值的作用。
    // 要改变值,就要传递地址,所以得传&thread_retval,因为thread_retval是一个指针,而&是取地址,所以就成了**的参数类型。
    ret = pthread_join(tid,(void **)&thread_retval);
    if(ret != 0)
    {
        char * str = strerror(ret);
        printf("error:%s\n",str);
    }
    printf("exit data:%d\n",*thread_retval);
    printf("回收子线程资源成功!\n");

    // 使用pthread_exit(NULL),不会影响其他正在运行的线程。
    pthread_exit(NULL);
    // main 线程退出后,下面的代码都会再执行
    printf("main thread end...\n");
    return 0;
}
qykhhr@qykhhr:~/Linux/lesson29$ gcc pthread_join.c -o pthread_join -pthread
qykhhr@qykhhr:~/Linux/lesson29$ ./pthread_join 
0
1
2
3
4
tld:140017165227776, main thread id:140017173743424
child thread ID = 140017165227776
exit data:10
回收子线程资源成功!

int pthread_detach(pthread_t thread);

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

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

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void * callback(void * arg)
{
    printf("child thread id:%ld\n",pthread_self());
    pthread_exit(NULL);// 等于 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);
    }

    // 设置分离后,对分离的子线程进行连接 pthread_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;
}
qykhhr@qykhhr:~/Linux/lesson29$ gcc pthread_detach.c -o pthread_detach -pthread
qykhhr@qykhhr:~/Linux/lesson29$ ./pthread_detach 
tid:139904826025728, main thread id:139904834541376
error3:Invalid argument
child thread id:139904826025728

int pthread_cancel(pthread_t thread);

#include <pthread.h>
int pthread_cancel(pthread_t thread);
功能:取消线程(让线程终止)
取消某个线程,可以终止某个线程的运行
但是并不是立马终止,而是当子线程执行到一个取消点,线程才会终止。
取消点:系统规定好的一些系统调用,我们可以粗略的理解为从用户态到内核态的切换,这个位置称之为取消点。

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

*/
#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 thread i:%d\n",i);
    }
    pthread_exit(NULL);// 等于 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;
}
qykhhr@qykhhr:~/Linux/lesson29$ gcc -o pthread_cancel pthread_cancel.c -pthread
qykhhr@qykhhr:~/Linux/lesson29$ ls
pthread_cancel  pthread_cancel.c  pthread_create  pthread_create.c  pthread_detach  pthread_detach.c  pthread_exit  pthread_exit.c  pthread_join  pthread_join.c
qykhhr@qykhhr:~/Linux/lesson29$ ./pthread_cancel 
0
1
2
3
4
tid:140298101294848, main thread id:140298109810496
child thread id:140298101294848
qykhhr@qykhhr:~/Linux/lesson29$ ./pthread_cancel 
child thread id:139960550348544
child thread i:0
child thread i:1
child thread i:2
child thread i:3
child thread i:4
0
1
2
3
4
tid:139960550348544, main thread id:139960558864192
qykhhr@qykhhr:~/Linux/lesson29$

7、线程属性

线程属性类型 pthread_attr_t

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

设置线程分离的状态属性

/*
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());
    pthread_exit(NULL);// 等于 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);
    int ret = pthread_create(&tid,&attr,callback,NULL);
    if(ret != 0)
    {
        char * errstr = strerror(ret);
        printf("error1:%s\n",errstr);
    }
    
    // 获取线程的栈的大小
    size_t size;
    pthread_attr_getstacksize(&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;
}1
qykhhr@qykhhr:~/Linux/lesson29$ gcc -o pthread_attr pthread_attr.c -pthread
qykhhr@qykhhr:~/Linux/lesson29$ ./pthread_attr 
thread stack size:8388608
tid:140330550847232, main thread id:140330559362880
child thread id:140330550847232

二、线程同步

1、线程同步概述

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

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

线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处于等待状态。

卖票 - 线程安全问题

使用多线程实现卖票的案例
有3个窗口,一共是100张票

/*
使用多线程实现卖票的案例
有3个窗口,一共是100张票
*/
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// 全局变量,所有线程都共享这一份资源
int tickets = 100;
void * sellticket(void * args)
{
    // 卖票

    while(tickets > 0)
    {
        // 睡眠3000微秒
        usleep(3000);
        printf("%ld 正在卖 %d 张门票\n",pthread_self(),tickets);
        tickets--;
    }
    return NULL; // 等价于 pthread_exit(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_join() 回收子线程资源是错误的。
    // pthread_detach(tid1);
    // pthread_detach(tid2);
    // pthread_detach(tid3);
    
    // 退出main线程,子线程不受影响,pthread_exit()函数后面的代码都不会再执行
    pthread_exit(NULL);
    return 0;
}

会出现多个窗口卖出同一张票,也会出现票卖出负数的情况

139723474278144 正在卖 13 张门票
139723482670848 正在卖 12 张门票
139723465885440 正在卖 11 张门票
139723482670848 正在卖 10 张门票
139723474278144 正在卖 9 张门票
139723465885440 正在卖 8 张门票
139723474278144 正在卖 7 张门票
139723465885440 正在卖 6 张门票
139723482670848 正在卖 5 张门票
139723482670848 正在卖 4 张门票
139723474278144 正在卖 3 张门票
139723465885440 正在卖 4 张门票
139723474278144 正在卖 1 张门票
139723482670848 正在卖 0 张门票
139723465885440 正在卖 -1 张门票

2、互斥量

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

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

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

  • 针对共享资源锁定互斥量
  • 访问共享资源
  • 对互斥量解锁

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

在这里插入图片描述

3、互斥量相关操作函数

互斥量的类型 pthread_mutex_t

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

初始化互斥量
参数:
mutex:需要初始化的互斥量变量
attr:互斥量相关的属性,NULL
restrict:C语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作。
pthread_mutex_t *restrict mutex = xxx;
pthread_mutex_t *mutex1 = mutex; // 错误

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

给互斥量解锁

通过信号量实现卖票过程中的线程安全问题

/*
互斥量的类型 pthread_mutex_t
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
    初始化互斥量
    参数:
        mutex:需要初始化的互斥量变量
        attr:互斥量相关的属性,NULL
    restrict:C语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作。
        pthread_mutex_t *restrict mutex = xxx;
        pthread_mutex_t *mutex1 = mutex; // 错误
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 <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// 全局变量,所有线程都共享这一份资源
int tickets = 1000;
// 创建一个全局的互斥量
pthread_mutex_t mutex;

void * sellticket(void * args)
{
    
    // 卖票
    while(1)
    {
        // 加锁
        pthread_mutex_lock(&mutex);
        
        if(tickets > 0)
        {
            // 睡眠3000微秒
            usleep(6000);
            printf("%ld 正在卖 %d 张门票\n",pthread_self(),tickets);
            tickets--;
        }
        else
        {
            // 退出循环之前也需要解锁
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }
        // 解锁
        pthread_mutex_unlock(&mutex);
        // 释放锁后睡眠3000微妙,可以更好地让其他线程夺取锁
        usleep(6000);
    }
    
    return NULL; // 等价于 pthread_exit(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_detach(tid1);
    // pthread_detach(tid2);
    // pthread_detach(tid3);

    // 和一个已经终止的线程进行连接,回收子线程资源,是阻塞的;
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL); 

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

    // 退出main线程,子线程不受影响,pthread_exit()函数后面的代码都不会再执行
    pthread_exit(NULL);

    return 0;
}
......
140270763071232 正在卖 9 张门票
140270754678528 正在卖 8 张门票
140270746285824 正在卖 7 张门票
140270763071232 正在卖 6 张门票
140270754678528 正在卖 5 张门票
140270746285824 正在卖 4 张门票
140270763071232 正在卖 3 张门票
140270754678528 正在卖 2 张门票
140270746285824 正在卖 1 张门票

4、死锁

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

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

死锁的几种场景:

  • 忘记释放锁
  • 重复加锁
  • 多线程多锁,抢占锁资源

在这里插入图片描述

忘记释放锁

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// 全局变量,所有线程都共享这一份资源
int tickets = 1000;
// 创建一个全局的互斥量
pthread_mutex_t mutex;

void * sellticket(void * args)
{
    
    // 卖票
    while(1)
    {
        // 加锁
        pthread_mutex_lock(&mutex);
        
        if(tickets > 0)
        {
            // 睡眠3000微秒
            usleep(6000);
            printf("%ld 正在卖 %d 张门票\n",pthread_self(),tickets);
            tickets--;
        }
        else
        {
            // 退出循环之前也需要解锁
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }
        // 解锁,忘记解锁就会出现阻塞
        // pthread_mutex_unlock(&mutex);
        // 释放锁后睡眠3000微妙,可以更好地让其他线程夺取锁
        usleep(6000);
    }
    
    return NULL; // 等价于 pthread_exit(NULL);
}

卖出第一张票后就会一直在加锁出阻塞等待加锁。

qykhhr@qykhhr:~/Linux/lesson30$ ./deadlock 
139846605473536 正在卖 1000 张门票

重复加锁

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// 全局变量,所有线程都共享这一份资源
int tickets = 1000;
// 创建一个全局的互斥量
pthread_mutex_t mutex;

void * sellticket(void * args)
{
    
    // 卖票
    while(1)
    {
        // 重复加锁
        pthread_mutex_lock(&mutex);
        // 就会阻塞在第二次加锁过程中
        pthread_mutex_lock(&mutex);
        
        if(tickets > 0)
        {
            // 睡眠3000微秒
            usleep(6000);
            printf("%ld 正在卖 %d 张门票\n",pthread_self(),tickets);
            tickets--;
        }
        else
        {
            // 退出循环之前也需要解锁
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }
        // 解锁,忘记解锁就会出现阻塞
        pthread_mutex_unlock(&mutex);
        pthread_mutex_unlock(&mutex);
        // 释放锁后睡眠3000微妙,可以更好地让其他线程夺取锁
        usleep(6000);
    }
    
    return NULL; // 等价于 pthread_exit(NULL);
}
qykhhr@qykhhr:~/Linux/lesson30$ gcc -o deadlock deadlock.c -pthread
qykhhr@qykhhr:~/Linux/lesson30$ ./deadlock 

多线程多锁,抢占锁资源

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

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

void * workA(void * arg)
{
    pthread_mutex_lock(&mutex1);
    // 等待workB 拿到 mutex2 互斥量
    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);
    // 等待workB 拿到 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;
}
qykhhr@qykhhr:~/Linux/lesson30$ gcc -o deadlock deadlock.c -pthread
qykhhr@qykhhr:~/Linux/lesson30$ ./deadlock 

5、读写锁

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

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

读写锁的特点:

  • 如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作。
  • 如果有其它线程写数据,则其它线程都不允许读、写操作。
  • 写是独占的,写的优先级高。

6、读写锁相关操作函数

读写锁的类型 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 *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_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

使用普通锁实现8个线程操作同一个全局变量

案例:8个线程操作同一个全局变量。3个线程不定时写这个全局变量,5个线程不定时的读这个全局变量。

/*
读写锁的类型 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 *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_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);  

案例:8个线程操作同一个全局变量。
    3个线程不定时写这个全局变量,5个线程不定时的读这个全局变量
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 创建一个共享数据
int num = 1;

// 创建一个普通的锁
pthread_mutex_t mutex;

void * writeNum(void * arg)
{
    while(1)
    {
        // 加锁
        pthread_mutex_lock(&mutex);
        num++;
        printf("++write, tld=%ld, num=%d\n",pthread_self(),num);
        // 解锁
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }
    return NULL;
}
void * readNum(void * arg)
{
     while(1)
    {
        pthread_mutex_lock(&mutex);
        printf("read, tld=%ld, num=%d\n",pthread_self(),num);
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }
    return NULL;
}

int main()
{
    // 初始化锁
    pthread_mutex_init(&mutex,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_mutex_destroy(&mutex);
    
    pthread_exit(NULL);
    return 0;
}
read, tld=140713368184576, num=25633
++write, tld=140713233966848, num=25634
++write, tld=140713376577280, num=25635
read, tld=140713343006464, num=25635
read, tld=140713359791872, num=25635
++write, tld=140713384969984, num=25636
read, tld=140713262053120, num=25636
read, tld=140713351399168, num=25636
read, tld=140713368184576, num=25636
++write, tld=140713233966848, num=25637
++write, tld=140713376577280, num=25638
read, tld=140713343006464, num=25638
read, tld=140713359791872, num=25638
++write, tld=140713384969984, num=25639
read, tld=140713351399168, num=25639
read, tld=140713262053120, num=25639
read, tld=140713368184576, num=25639

使用读写锁

/*
读写锁的类型 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 *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_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);  

案例:8个线程操作同一个全局变量。
    3个线程不定时写这个全局变量,5个线程不定时的读这个全局变量
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 创建一个共享数据
int num = 1;

// 创建一个普通的锁
pthread_mutex_t mutex;
// 创建一个读写锁
pthread_rwlock_t rwlock;

void * writeNum(void * arg)
{
    while(1)
    {
        // 加锁
        // pthread_mutex_lock(&mutex);
        // 加写锁
        pthread_rwlock_wrlock(&rwlock);
        num++;
        printf("++write, tld=%ld, num=%d\n",pthread_self(),num);
        // 解锁
        // pthread_mutex_unlock(&mutex);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
    return NULL;
}
void * readNum(void * arg)
{
     while(1)
    {
        // pthread_mutex_lock(&mutex);
        // 加读锁
        pthread_rwlock_rdlock(&rwlock);
        printf("read, tld=%ld, num=%d\n",pthread_self(),num);
        // pthread_mutex_unlock(&mutex);
        // 解除读锁
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
    return NULL;
}

int main()
{
    // 初始化锁
    // pthread_mutex_init(&mutex,NULL);

    // 初始化读写锁
    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_mutex_destroy(&mutex);

    pthread_rwlock_destroy(&rwlock);
    
    pthread_exit(NULL);
    return 0;
}
......
read, tld=139918513166080, num=12435
read, tld=139918416275200, num=12435
read, tld=139918424667904, num=12435
++write, tld=139918521558784, num=12436
++write, tld=139918538344192, num=12437
read, tld=139918407882496, num=12437
read, tld=139918416275200, num=12437
read, tld=139918504773376, num=12437
read, tld=139918513166080, num=12437
++write, tld=139918529951488, num=12438
++write, tld=139918521558784, num=12439
++write, tld=139918538344192, num=12440
read, tld=139918504773376, num=12440
......

7、生产者消费者模型

在这里插入图片描述

生产者消费者模型(粗略的版本)

生产者在队列满了的情况下不能再生产,消费者在队列为空时不能再消费。

/*
生产者消费者模型(粗略的版本)
*/
#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("del node, num=%d, tid=%ld\n",tmp->num,pthread_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(NULL);
    return 0;
}
qykhhr@qykhhr:~/Linux/lesson30$ gcc -o prodcust prodcust.c -pthread
qykhhr@qykhhr:~/Linux/lesson30$ ./prodcust 
add node, num=383, tid=140414235739904
del node, num=383, tid=140414210561792
add node, num=886, tid=140414067951360
del node, num=886, tid=140414202169088
add node, num=777, tid=140414176990976
del node, num=777, tid=140414227347200
add node, num=915, tid=140414067951360
add node, num=335, tid=140414218954496
del node, num=335, tid=140414210561792
add node, num=793, tid=140414193776384
add node, num=386, tid=140414235739904
add node, num=492, tid=140414176990976
段错误 (核心已转储)

查看段错误

首先使用ulimit -a查看 core file size是否为0,如果是0需要使用ulimit -c 1024修改为大于0值(1024),然后使用gcc -o xxx xxx.c -g -pthread生成带有调试信息的可执行程序,执行生成的程序,然后查看 core 文件是否生成,最后通过gdb xxx,使用 gdb 工具来查看 core 文件。

使用互斥量加锁

/*
生产者消费者模型(粗略的版本)
*/
#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("del node, num=%d, tid=%ld\n",tmp->num,pthread_self());
            // 释放指针
            free(tmp);
        }
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }
    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]);

        // 设置阻塞等待连接子线程回收资源,可以一直在这里阻塞等待,结束后,自然就会销毁互斥量
        pthread_join(ptids[i],NULL);
        pthread_join(ctids[i],NULL);
    }
    
    // pthread_detach:设置线程分离,就会立刻执行销毁互斥量,我们不能销毁,因为互斥量还在使用,我们需要阻塞
    // pthread_join:设置线程连接,回收子线程资源时,是阻塞的,我们就不行这个循环来阻塞了
    //while (1)
    //{
    //    sleep(1);
    //}
     // 释放互斥量,互斥量销毁后不能使用了,我需要再此之前进行循环等待
    pthread_mutex_destroy(&mutex);
    
    // 设置主线程退出后,进程不会停止
    pthread_exit(NULL);
    return 0;
}
qykhhr@qykhhr:~/Linux/lesson30$ ./prodcust 
add node, num=373, tid=139780859897600
del node, num=373, tid=139780868290304
add node, num=90, tid=139780826326784
del node, num=90, tid=139780834719488
add node, num=969, tid=139780893468416
add node, num=260, tid=139780826326784
del node, num=260, tid=139780868290304
add node, num=991, tid=139780843112192
del node, num=991, tid=139780834719488
add node, num=545, tid=139780876683008
del node, num=545, tid=139780851504896
del node, num=969, tid=139780817934080
add node, num=609, tid=139780859897600
......

8、条件变量

条件变量的类型 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);

使用条件变量实现生产者通知消费者,消费者等待生产者

// 只要生产了一个,就通知消费者消费
pthread_cond_signal(&cond);

// 这个函数调用阻塞的时候,会对互斥锁进行解锁,当不阻塞时,继续向下执行,会重新加锁
pthread_cond_wait(&cond,&mutex);
/*
条件变量的类型 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);  
    唤醒所有的等待的线程
*/
/*
生产者消费者模型(粗略的版本)
*/
#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);

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

        // 设置阻塞等待连接子线程回收资源,可以一直在这里阻塞等待,结束后,自然就会销毁互斥量
        pthread_join(ptids[i],NULL);
        pthread_join(ctids[i],NULL);
    }
    // pthread_detach:设置线程分离,就会立刻执行销毁互斥量,我们不能销毁,因为互斥量还在使用,我们需要阻塞
    // pthread_join:设置线程连接,回收子线程资源时,是阻塞的,我们就不行这个循环来阻塞了
    //while (1)
    //{
    //    sleep(1);
    //}
    
    // 释放互斥量,互斥量销毁后不能使用了,我需要再此之前进行循环等待
    pthread_mutex_destroy(&mutex);
    // 释放条件变量
    pthread_cond_destroy(&cond);

    // 设置主线程退出后,进程不会停止
    pthread_exit(NULL);
    return 0;
}
......
del node, num=449, tid=140241209911040
add node, num=281, tid=140241167947520
del node, num=281, tid=140241176340224
add node, num=456, tid=140241184732928
add node, num=277, tid=140241235089152
add node, num=350, tid=140241167947520
del node, num=350, tid=140241193125632
del node, num=277, tid=140241209911040
del node, num=456, tid=140241226696448
del node, num=991, tid=140241159554816
......

9、信号量

信号量的类型 sem_t
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_destroy(sem_t *sem);
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
int sem_post(sem_t *sem);
int sem_getvalue(sem_t *sem, int *sval);

/*
信号量的类型 sem_t
int sem_init(sem_t *sem, int pshared, unsi gned 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);  

伪代码:
sem_t psem;
sem_t csem;
init(psem, 0, 8);
init(csem, 0, 0);

producer() {
    sem_wait(&psem);
    sem_post(&csem)
}

customer() {
    sem_wait(&csem);
    sem_post(&psem)
}
*/
#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)
    {
        // 对信号量加锁,调用一次对信号量的值-1,如果值为0,就阻塞
        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
        sem_post(&csem);
    }
    return NULL;
}
void * customer(void * arg)
{
    // 不断的创建新的节点,采用头插法添加到链表中
    while(1)
    {
        // 默认是0,会阻塞,等待生产者将 csem 信号量+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(1);
    }
    // 释放互斥量,互斥量销毁后不能使用了,我需要再此之前进行循环等待
    pthread_mutex_destroy(&mutex);
    // 设置主线程退出后,进程不会停止
    pthread_exit(NULL);
    return 0;
}
......
add node, num=623, tid=139857951188736
del node, num=623, tid=139857926010624
add node, num=773, tid=139857934403328
add node, num=940, tid=139858055538432
del node, num=940, tid=139858047145728
del node, num=773, tid=139858047145728
del node, num=489, tid=139858047145728
add node, num=12, tid=139858038753024
add node, num=552, tid=139858055538432
add node, num=168, tid=139857917617920
......
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <semaphore.h>

// 创建两个信号量
sem_t psem;
sem_t csem;

struct Node
{
    int num;
    struct Node * next;
};
struct Node * head = NULL;
void * product(void * arg)
{
    // 不断地创建新的节点,采用头插法添加到链表中
    while (1)
    {
        // 对信号量枷锁,调用一次对信号量的值 -1,如果值为0,就阻塞
        sem_wait(&psem);

        struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));    
        newNode->num = rand() % 1000;
        newNode->next = head;
        head = newNode;
        printf("product thread add node, id = %ld, num = %d!\n",pthread_self(),newNode->num);
        
        // 对信号量解锁,调用一次对信号量+1
        sem_post(&csem);
    }
    return NULL;
}
void * customer(void * arg)
{
    // 不断的移除头节点
    while (1)
    {
        // 默认是0,会阻塞,等待生产者将 csem 信号量+1,这里才会继续执行
        sem_wait(&csem);
        if(head != NULL)
        {
            struct Node * temp = head;
            // 链表中有数据,我们可以删除
            head = head->next;
            printf("customer thread del node,id = %ld, num = %d!\n",pthread_self(),temp->num);
            // 释放指针
            free(temp);
        }
        // 告诉生产者,当前已经有一个被使用了,可以再生产了
        sem_post(&psem);
    }
    return NULL;
}
int main()
{
    // 初始化信号量
    // 这里初始值要设为1,否则,生产者阻塞了,就不能生产了
    sem_init(&psem,0,1);
    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,product,NULL);
        pthread_create(&ctids[i],NULL,customer,NULL);
    }

    // 设置线程分离
    for(int i = 0; i < 5; i++)
    {
        // 这里设置线程分离后,下面就不能销毁全局互斥量,需要一直使用这个互斥量
        // pthread_detach(ptids[i]);
        // pthread_detach(ctids[i]);

        // 设置阻塞等待连接子线程回收资源,可以一直在这里阻塞等待,结束后,自然就会销毁互斥量
        pthread_join(ptids[i],NULL);
        pthread_join(ctids[i],NULL);
    }

    // 销毁全局信号量
    sem_destroy(&psem);
    sem_destroy(&csem);

    // 退出 main 线程
    pthread_exit(NULL);
    return 0;
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值