Linux 多线程

Linux线程概念

什么是线程

  • 在一个程序里的一个执行路线就叫做线程(thread)。更准确的定义是:线程是"一个进程内部的控制序列"
  • 一切进程至少都有一个执行线程线程在进程内部运行,本质是在进程地址空间内运行
  • 在Linux系统中,在CPU眼中,看到的PCB都要比传统的进程更加轻量化
  • 透过进程虚拟地址空间,可以看到进程的大部分资源,将进程资源合理分配给每个执行流,就形成了线程执行流

总结:线程是进程内的一个执行分支,(进程内的一个执行流)线程的执行粒度,要比进程细

Linux下理解线程

进程看到的大部分资源,都是通过进程地址空间,所以进程地址空间就是资源窗口

创建一个子进程 没有进程地址空间 页表 也不会映射到物理内存,和父进程共享同一份资源

创建多个子进程,只和父进程共享地址空间,让它们去执行父进程的一部分代码资源

所有创建的子进程包括父进程,都可以对该地址空间进程一定程度的分享

以上的操作,相比之前的创建子进程执行的粒度要更细一些,这些子进程跑的是父进程中代码的一部分,为了和之前创建子进程进行区分,我们将这样的子进程称为:线程

此时我们创建的实际上就是四个线程:

• 其中每一个线程都是当前进程里面的一个执行流,也就是我们常说的 "线程是进程内部的一个执行分支" 。

• 同时我们也可以看出,线程在进程内部运行,本质就是线程在进程地址空间内运行,也就是说曾经这个进程申请的所有资源,几乎都是被所有线程共享的,本质就是分配进程地址空间的范围。

注意: 单纯从技术角度,这个是一定能实现的,因为它比创建一个原始进程所做的工作更轻量化了。

在Linux中,站在CPU的角度,能否识别当前调度的task_struct是进程还是线程?

答案显然是不行,也不需要,在CPU的角度,不会区别进程和线程(因为它不知道),它只有调度执行流(线程 <= 执行流 <= 进程)的概念

多执行流进程被调度:

因此,CPU看到的虽说还是task_struct,但已经比传统的进程要更轻量化了。

1.Linux下 什么叫做线程在进程"内部"执行?

线程在进程的地址空间内运行(为什么?任何执行流运行都需要资源 ,进程地址空间是资源窗口)实际上就是在该进程的进程地址空间上运行

任何进程获取资源只有两个方式:

1.将进程的资源拷贝一份给自己 (子进程方式)

2.和进程共享同一份资源 (线程方式)

2.Linux下 线程的执行粒度为什么比进更细?

线程执行进程代码的一部分,所处于同一份地址空间

重新定义线程和进程

线程:线程是系统调度的基本单位

原先理解:进程 = 内核数据结构(task_struct) + 进程地址空间 + 页表 + 代码和数据

打碎重新理解:进程 = 所有pcb内核数据结构 + 进程地址空间 + 页表 + 映射物理内存的一小部分空间

内核观点:进程是承担操作系统分配资源的基本实体

如何理解之前的进程?

操作系统以进程为单位分配资源,只是我们当前的进程内部只有一个执行流资源(线程)

创建进程时,建立进程地址空间 页表映射物理内存不就是操作系统给你分配和初始化资源吗,所以创建一个执行流来使用,和多个执行流来使用是一样的

Linux下并不存在真正的多线程!而是用进程模拟的!

操作系统中存在大量的进程,一个进程内又存在一个或多个线程,因此线程的数量一定比进程的数量多,当线程的数量足够多的时候,很明显线程的执行粒度要比进程更细。

如果一款操作系统要支持真的线程,那么就需要对这些线程进行管理。比如说创建线程id、终止线程、调度线程、切换线程、给线程分配资源、释放资源以及回收资源等等、所有的这一套相比较进程都需要另起炉灶,搭建一套与进程平行的线程管理模块。

因此,如果要支持真的线程一定会提高设计操作系统的复杂程度。在Linux看来,描述线程的控制块和描述进程的控制块是类似的,因此Linux并没有重新为线程设计数据结构,而是直接复用了进程控制块以及进程的管理算法,所以我们说Linux中的所有执行流都叫做轻量级进程。但也有支持真的线程的操作系统,比如Windows操作系统,因此Windows操作系统系统的实现逻辑一定比Linux操作系统的实现逻辑要复杂得多,这种方式也使得Linux的健壮性极其强大,维护成本低,出问题修复问题的成本低,效率大大提高

既然在Linux没有真正意义的线程,那么也就绝对没有真正意义上的线程相关的系统调用!

这很好理解,既然在Linux中都没有真正意义上的线程了,那么自然也没有真正意义上的线程相关的系统调用了。但是Linux可以提供创建轻量级进程的接口,也就是创建进程,共享空间,其中最典型的代表就是vfork函数。

vfork函数的功能就是创建子进程,但是父子共享空间,vfork的函数原型如下:

cpp 复制代码
pid_t vfork(void);

vfork函数的返回值与fork函数的返回值相同:

• 给父进程返回子进程的PID。

• 给子进程返回0。

cpp 复制代码
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

using namespace std;

int gval = 100;

int main()
{
    pid_t id = vfork();    
    if(id == 0)
    {
        gval = 200;
        printf("child gval: %d\n", gval);
        exit(0);
    }

    printf("parent gval: %d\n", gval);
    waitpid(id, nullptr, 0);


    return 0;
}

二级页表

以32位平台为例,在32位平台下一共有2^32个地址,也就意味着有2^32个地址需要被映射。

如果我们所谓的页表就只是单纯的一张表,那么这张表就需要建立2^32个虚拟地址和物理地址之间的映射关系,即这张表一共有2^32个映射表项。

每一个表项中除了要有虚拟地址和与其映射的物理地址以外,实际还需要有一些权限相关的信息,比如我们所说的用户级页表和内核级页表,实际就是通过权限进行区分的。

  1. 物理地址:这一列记录的是内存中的物理地址,"XXX" 是具体物理地址的占位符,在实际应用中会被真实的地址值所替代。物理地址是内存中存储单元的绝对地址,用于在硬件层面定位数据存储位置。
  2. 是否命中:这一列表示在进行某种内存访问操作(比如缓存查找、虚拟 - 物理地址转换等)时,是否成功找到对应的物理地址。"是" 表示成功命中,即找到了需要访问的物理地址;如果是 "否" ,则表示未命中。
  3. RWX 权限:这一列表示对该物理地址所指向的存储单元的访问权限。"R" 代表读(Read)权限,即可以读取存储单元中的数据;"W" 代表写(Write)权限,即可以向存储单元中写入数据;"X" 代表执行(Execute)权限,即可以执行存储单元中的可执行代码。第一行 "RW" 表示具有读和写权限,第二行 "R" 表示只有读权限。
  4. U/K 权限:"U" 代表用户(User)模式权限,"K" 代表内核(Kernel)模式权限。这一列表示该物理地址在用户模式或内核模式下的访问权限。第一行和第二行中的 "U" 表示该物理地址在用户模式下可以访问。

每个应表项中存储一个物理地址和一个虚拟地址就需要8个字节,考虑到还需要包含权限相关的各种信息,这里每一个表项就按10个字节计算。

这里一共有232个表项,也就意味着存储这张页表我们需要用232 * 10个字节,也就是40GB。而在32位平台下我们的内存可能一共就只有4GB,也就是说我们根本无法存储这样的一张页表。

因此所谓的页表并不是单纯的一张表。

还是以32位平台为例,其页表的映射过程如下:

  1. 选择虚拟地址的前10个比特位在页目录当中进行查找,找到对应的页表。

  2. 再选择虚拟地址的10个比特位在对应的页表当中进行查找,找到物理内存中对应页框的起始地址。

  3. 最后将虚拟地址中剩下的12个比特位作为偏移量从对应页框的起始地址处向后进行偏移,找到物理内存中某一个对应的字节数据。

相关说明:

  1. 物理内存实际是被划分成一个个4KB大小的页框的,而磁盘上的程序也是被划分成一个个4KB大小的页帧的,当内存和磁盘进行数据交换时也就是以4KB大小为单位进行加载和保存的。

  2. 4KB实际上就是2^12个字节,也就是说一个页框中有2^12个字节,而访问内存的基本大小是1字节,因此一个页框中就有2^12个地址,于是我们就可以将剩下的12个比特位作为偏移量,从页框的起始地址处开始向后进行偏移,从而找到物理内存中某一个对应字节数据。

这实际上就是我们所谓的二级页表,其中页目录是一级页表,页表项是二级页表。

我们按照页表全部都为满的情况来算一下,现在这种形式的页表所需的空间大小是都多少

页表项所占大小:4字节 * 1024 = 4KB 页目录全满情况下页表所占大小:4KB * 1024 = 4MB,相较于40GB已经有极大的改进了

上面所说的所有映射过程,都是由MMU(MemoryManagementUnit)这个硬件完成的,该硬件是集成在CPU内的。页表是一种软件映射,MMU是一种硬件映射,所以计算机进行虚拟地址到物理地址的转化采用的是软硬件结合的方式。

在C语言中int,float,double类型怎么办?

int是4个字节4个地址,为什么&a只有一个地址,其实不管是内置类型还是自定义类型都只有一个地址,即:它们在空间中的起始地址,找到这个地址往上读取该类型大小字节(起始地址+类型=起始地址+偏移量)来拿到该类型所对应的值,以上的工作都是由CPU做的

修改常量字符串为什么会触发段错误?

当我们要修改一个字符串常量时,虚拟地址必须经过页表映射找到对应的物理内存,而在查表过程中发现其权限是只读的,此时你要对其进行修改就会在MMU内部触发硬件错误,操作系统在识别到是哪一个进程导致的之后,就会给该进程发送信号对其进行终止,该虚拟地址会放在cr2寄存器中存储。

cr2寄存器:保存进行越界,... 引起缺页中断,异常的虚拟地址

为什么线程比进程要更轻量化?

a. 创建和释放更加轻量化

创建线程只需要创建PCB就可以,创建进程不仅需要创建PCB还需要创建进程地址空间, 页表映射物理内存以及关于信号的三张图等等...

b. 切换更加轻量化(运行)

进程上下文保护

线程页表进程地址空间都不需要切换,切换效率高

计算机组成原理解释

线程的执行本质就是进程的执行,线程是进程的一个执行分支,线程在执行就是进程在调度,在cpu中有一个硬件级别的缓存cache(缓存热数据(数据被高频访问)CPU会将高频访问的数据放在这个寄存器中) 在进行线程切换时,切换的是一个进程中的多个线程,在切换时虽然上下文一直在变化,但是缓存中的数据一直不变,或少量更新,因为线程中很多属性都是被共享的,这种设计就是为了让多个线程同时访问,提高效率

如果一个进程上的线程和进程时间片全部到耗尽,那么进程就需要被调度,进行切换,它的cache寄存器上的热缓存数据会被丢弃掉(由冷变热),这就是为什么线程切换的效率更高,因为cache寄存器上的数据不会由冷变热,线程内切换不需要重新进行缓存cache数据

线程也需要有自己的时间片(来自进程),操作系统不会给线程重新分配时间片,而是将进程的时间片平均到每个线程上,如果给每个线程重新分配时间片,就会导致该进程的时间片变多(不合理)

怎么判断线程还是进程的时间片到期?

所以我们将刚启动的线程叫做主线程(记录时间片总时间),其他线程进行调度时时间片减少,对应的主线程的时间片也在减少

线程的优点

• 创建一个新线程的代价要比创建一个新进程小得多。

• 与进程之间的切换相比,线程之间的切换需要操作系统做的工作要少很多。

• 线程占用的资源要比进程少很多。

• 能充分利用多处理器的可并行数量。

• 在等待慢速IO操作结束的同时,程序可执行其他的计算任务。

• 计算密集型应用,为了能在多处理器系统上运行,将计算分解到多个线程中实现。

• IO密集型应用,为了提高性能,将IO操作重叠,线程可以同时等待不同的IO操作。

概念说明:

• 计算密集型:执行流的大部分任务,主要以计算为主。比如加密解密、大数据查找等。

• IO密集型:执行流的大部分任务,主要以IO为主。比如刷磁盘、访问数据库、访问网络等。

线程的缺点

• 性能损失:

一个很少被外部事件阻塞的计算密集型线程往往无法与其他线程共享同一个处理器。如果计算密集型线程的数量比可用的处理器多,那么可能会有较大的性能损失,这里的性能损失指的是增加了额外的同步和调度开销,而可用的资源不变。
• 健壮性降低:

编写多线程需要更全面更深入的考虑,在一个多线程程序里,因时间分配上的细微偏差或者因共享了不该共享的变量而造成不良影响的可能性是很大的,换句话说,线程之间是缺乏保护的。
• 缺乏访问控制:

进程是访问控制的基本粒度,在一个线程中调用某些OS函数会对整个进程造成影响。
• 编程难度提高:

编写与调试一个多线程程序比单线程程序困难得多。

线程异常

单个线程如果出现除零,野指针问题导致线程崩溃,进程也会随着崩溃线程是进程的执行分支,线程出异常,就类似进程出异常,进而触发信号机制,终止进程,进程终止,该进程内的所有线程也就随即退出

线程用途

合理的使用多线程,能提高CPU密集型程序的执行效率 合理的使用多线程,能提高IO密集型程序的用户体验(如生活中我们一边写代码一边下载开发工具,就是 多线程运行的一种表现)

Linux进程VS线程

进程和线程

进程是资源分配的基本单位 线程是调度的基本单位

线程共享进程数据,但也拥有自己的一部分数据:

• 线程ID

一组寄存器。(存储每个线程的上下文信息)

栈。(每个线程都有临时的数据,需要压栈出栈)

• errno。(C语言提供的全局变量,每个线程都有自己的)

• 信号屏蔽字。

• 调度优先级。

进程的多个线程共享

因为是在同一个地址空间,因此所谓的代码段(Text Segment)、数据段(Data Segment)都是共享的:

• 如果定义一个函数,在各线程中都可以调用。

• 如果定义一个全局变量,在各线程中都可以访问到。

除此之外,各线程还共享以下进程资源和环境:

• 文件描述符表。(进程打开一个文件后,其他线程也能够看到)

• 每种信号的处理方式。(SIG_IGN、SIG_DFL或者自定义的信号处理函数)

• 当前工作目录。(cwd)

• 用户ID和组ID。

进程和线程的关系

进程和线程的关系如下图:

Linux 线程控制

POSIX线程库

  • pthread线程库是应用层的原生线程库:应用层指的是这个线程库并不是系统接口直接提供的,而是由第三方帮我们提供的,因为Linux中并没有真正意义上的线程,只有轻量级进程,所以我们就将轻量级进程进行封装提供给上层用户使用。
  • 原生指的是大部分Linux系统都会默认带上该线程库。
  • 与线程有关的函数构成了一个完整的系列,绝大多数函数的名字都是以"pthread_"打头的。
  • 要使用这些函数库,要通过引入头文件<pthreaad.h>。
  • 链接这些线程函数库时,要使用编译器命令的 "-lpthread" 选项。

错误检查:

  • 传统的一些函数是,成功返回0,失败返回-1,并且对全局变量errno赋值以指示错误。
  • pthreads函数出错时不会设置全局变量errno(而大部分POSIX函数会这样做),而是将错误代码通过返回值返回。
  • pthreads同样也提供了线程内的errno变量,以支持其他使用errno的代码。对于pthreads函数的错误,建议通过返回值来判定,因为读取返回值要比读取线程内的errno变量的开销更小。

线程创建

pthread_create函数用来创建线程

pthread_create函数原型如下:

cpp 复制代码
typedef unsigned long int pthread_t 
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

参数说明:

pthread_t *thread:输出型参数,获取创建成功的线程id

const pthread_attr_t *arr:用于设置创建线程的属性,传入NULL表示使用默认属性,一般都设置为nullptr。

void *(*start_routine)(void*):该参数是一个函数指针,线程启动后要执行的函数。

void *arg:传给系统启动函数的参数

返回值说明:

线程创建成功返回0,失败返回错误码。

让主线程创建一个新线程

当一个程序启动时,就有一个进程被操作系统创建,与此同时一个线程也立刻运行,这个线程就叫做主线程。

• 主线程是产生其他子线程的线程。

• 通常主线程必须最后完成某些执行操作,比如各种关闭动作。

下面我们让主线程调用pthread_create函数创建一个新线程,此后新线程就会跑去执行自己的新例程,而主线程则继续执行后续代码

cpp 复制代码
#include <iostream>
#include <pthread.h> //Linux 原生线程库
#include <unistd.h>

using namespace std;

void* threadRoutine(void* arg)
{
    while(true)
    {
        printf("%s success!\n", (char*)arg);
        sleep(1);
    }
    return 0;
}

int main()
{
    pthread_t pid;
    int n = pthread_create(&pid, nullptr, threadRoutine, (void*)"create thread!!!");
    if(n != 0)
    {
        perror("main::pthread_create");
        return 1;
    }

    while(true)
    {
        printf("I am main thread!!!\n");
        sleep(1);
    }

    return 0;
}

运行代码后可以看到,新线程和主线程每隔一秒执行一次打印操作

当我们用ps axj命令查看当前进程的信息时,虽然此时该进程中有两个线程,但是我们看到的进程只有一个,因为这两个线程都是属于同一个进程的。

使用ps -aL命令,可以显示当前的轻量级进程。

  • 默认情况下,不带-L,看到的就是一个个的进程。
  • 带-L就可以查看到每个进程内的多个轻量级进程。

其中,LWP(Light Weight Process)就是轻量级进程的ID,可以看到显示的两个轻量级进程的PID是相同的,因为它们属于同一个进程。

**注意:**在Linux中,应用层的线程与内核的LWP是一一对应的,实际上操作系统调度的时候采用的是LWP,而并非PID,只不过我们之前接触到的都是单线程进程,其PID和LWP是相等的,所以对于单线程进程来说,调度时采用PID和LWP是一样的。

为了进一步证明这两个线程是属于同一个进程的,我们可以让主线程和新线程在执行打印操作时,将自己的PID和PPID也进行打印。

为了进一步证明这两个线程是属于同一个进程的,我们可以让主线程和新线程在执行打印操作时,将自己的PID和PPID也进行打印。

cpp 复制代码
#include <iostream>
#include <pthread.h> //Linux 原生线程库
#include <unistd.h>

using namespace std;

void* threadRoutine(void* arg)
{
    while(true)
    {
        printf("thread -> pid: %d ppid: %d\n", getpid(), getppid());
        sleep(1);
    }
    return 0;
}

int main()
{
    pthread_t pid;
    int n = pthread_create(&pid, nullptr, threadRoutine, (void*)"create thread!!!");
    if(n != 0)
    {
        perror("main::pthread_create");
        return 1;
    }

    while(true)
    {
        printf("main thread -> pid: %d ppid: %d\n", getpid(), getppid());
        sleep(1);
    }

    return 0;
}

可以看到主线程和新线程的PID和PPID是一样的,也就是说主线程和新线程虽然是两个执行流,但它们仍然属于同一个进程,共享进程的pid和ppid。

主线程创建一堆线程

cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

struct threadData
{
    string threadname;
};

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    while(true)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
            getpid(), getppid(), pthread_self(), td->threadname.c_str());

        sleep(1);
    }

}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);   
}

int main()
{
    vector<pthread_t> tids;
    vector<threadData*> tData;
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td);
        InitThreadData(td, i);
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        tids.push_back(tid);
    }

    while(true)
    {
        printf("main thread!!!\n");

        sleep(1);
    }

    //释放申请资源
    for(auto td : tData) 
    {
        delete td;
    }

    return 0;
}

运行结果如下:

可以看到主线程和新线程的pid和ppid相同,因为它们同属一个进程

使用 ps -aL 我们可以看到六个轻量级进程

获取线程ID

常见获取线程ID的方式有两种:

  • 创建线程时通过输出型参数获得。
  • 通过调用pthread_self函数获得。

pthread_self函数的函数原型如下:

cpp 复制代码
pthread_t pthread_self(void);
cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

struct threadData
{
    string threadname;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    while(true)
    {
        printf("pid: %d, ppid: %d, tid: %ld %s\n",
            getpid(), getppid(), pthread_self(), td->threadname.c_str());
        sleep(1);
    }

}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);   
}

int main()
{
    vector<pthread_t> tids;
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, i);
        tids.push_back(tid);
    }

    while(true)
    {
        printf("main thread!!! pid %d, tid: %d\n", getpid(), pthread_self());

        sleep(1);
    }
    return 0;
}

运行代码,可以看到这两种方式获取到的线程的ID是一样的。

注意: 用pthread_self函数获得的线程ID与内核的LWP的值是不相等的,pthread_self函数获得的是用户级原生线程库的线程ID,而LWP是内核的轻量级进程ID,它们之间是一对一的关系。

线程等待

首先需要明确的是,一个线程被创建出来,这个线程就如同进程一般,也是需要被等待的。如果主线程不对新线程进行等待,那么这个新线程的资源也是不会被回收的。所以线程需要被等待,如果不等待会产生类似于"僵尸进程"的问题,也就是内存泄漏。

线程等待的函数 pthread_join

pthread_join函数原型如下:

cpp 复制代码
int pthread_join(pthread_t thread, void **retval);

参数说明:

  • thread:被等待线程的ID。
  • retval:线程退出时的退出码信息。

由于用户不能直接访问操作系统,pthread_join函数第二个参数retval它是如何将底层的返回值传递给用户层的?

**原理:**通过临时变量(二级指针)

**注意:**任何参数传参都会产生临时变量

返回值说明:

  • 线程等待成功返回0,失败返回错误码。

例如,在下面的代码中我们先不关心线程的退出信息,直接将pthread_join函数的第二次参数设置为nullptr,等待线程后打印该线程的编号以及线程ID。

调用该函数的线程将挂起等待,直到id为thread的线程终止。thread线程以不同的方法终止,通过pthread_join得到的终止状态是不同的,总结如下

总结如下:

  1. 如果thread线程通过return返回,retval所指向的单元里存放的是thread线程函数的返回值。

  2. 如果thread线程被别的线程调用pthread_cancel异常终止掉,retval所指向的单元里存放的是常数PTHREAD_CANCELED。

  3. 如果thread线程是自己调用pthread_exit终止的,retval所指向的单元存放的是传给pthread_exit的参数。

  4. 如果对thread线程的终止状态不感兴趣,可以传NULL给retval参数。

用grep命令进行查找,可以发现PTHREAD_CANCELED实际上就是头文件<pthread.h>里面的一个宏定义,它的值本质就是-1。

cpp 复制代码
grep -ER "PTHREAD_CANCELED" /usr/include/
cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
            getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());
        sleep(1);
    }

    return nullptr;
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    vector<pthread_t> tids;
    vector<pthreadData*> tData;
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td);
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);
        tids.push_back(tid);
    }

    int cnt = 5;
    while(cnt--)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

        sleep(1);
    }

    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        int n = pthread_join(tids[i], nullptr);
        if(n == 0)
        {
            printf("thread-%d wait success!\n", i);
        }
        else
            break;
    }

    //释放申请的资源
    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

运行代码后,可以看到主线程创建的五个新线程在进行五次打印操作后就退出了,而主线程也是成功对这五个线程进行了等待。

下面我们再来看看如何获取线程退出时的退出码,为了便于查看,我们这里将线程退出时的退出码设置为某个特殊的值,并在成功等待线程后将该线程的退出码进行输出。

cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
            getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());

        sleep(1);
    }

    return nullptr;
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);

        tids.push_back(tid);
    }

    int cnt = 5;
    while(cnt--)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

        sleep(1);
    }

    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        void* ExitCode = nullptr;
        int n = pthread_join(tids[i], &ExitCode);
        if(n == 0)
        {
            printf("thread-%lu wait success! exitcode: %d\n", tids[i], ExitCode);
        }
        else
            break;
    }

    //释放申请的资源
    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

运行代码,此时我们就拿到了每个线程退出时的退出码信息。

注意: pthread_join函数默认是以阻塞的方式进行线程等待的。

线程怎么不像进程一样设置退出信号异常退出?

因为线程做不到,如果某一个线程出现异常进行了资源的释放,异常退出,那么整个进程都会退出

例如,我们在线程的执行例程当中制造一个除零错误,当某一个线程执行到此处时就会崩溃,进而导致整个进程崩溃。

cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
            getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());

        int a = 10;
        a /= 0;
        
        sleep(1);
    }

    return nullptr;
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);

        tids.push_back(tid);
    }

    int cnt = 5;
    while(cnt--)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

        sleep(1);
    }

    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        void* ExitCode = nullptr;
        int n = pthread_join(tids[i], &ExitCode);
        if(n == 0)
        {
            printf("thread-%lu wait success! exitcode: %d\n", tids[i], ExitCode);
        }
        else
            break;
    }

    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

运行代码,可以看到一旦某个线程崩溃了,整个进程也就跟着挂掉了,此时主线程连等待新线程的机会都没有,这也说明了多线程的健壮性不太强,一个进程中只要有一个线程挂掉了,那么整个进程就挂掉了。并且此时我们也不知道是由于哪一个线程崩溃导致的,我们只知道是这个进程崩溃了。

所以pthread_join函数只能获取到线程正常退出时的退出码,用于判断线程的运行结果是否正确。

线程终止

如果需要只终止某个线程而不是终止整个进程,可以有三种方法:

1.在线程函数内部使用return放回

2.使用pthread_exit()函数来进行对线程的终止

3.使用pthread_cancel()函数取消线程

在线程函数内部使用return放回

cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5

struct threadData
{
    string threadname;
    pthread_t tid;
};

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %ld %s\n",
            getpid(), getppid(), pthread_self(), td->threadname.c_str());

        sleep(1);
    }

    return nullptr;
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, i);
        tids.push_back(tid);
    }

    printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

    usleep(1000);
    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

运行代码,并不能看到新线程后续的打印操作,因为主线程的退出导致整个进程退出了。

pthread_exit函数

pthread_exit函数的功能就是终止线程,pthread_exit函数的函数原型如下:

cpp 复制代码
void pthread_exit(void *retval);

参数说明:

  • retval:线程退出时的退出码信息

说明一下:

  • 该函数无返回值,跟进程一样,线程结束的时候无法返回它的调用者(自身)。
  • pthread_exit或者return返回的指针所指向的内存单元必须是全局的或者是用malloc分配的,不能在线程函数的栈上分配,因为当其他线程得到这个返回指针时,线程函数已经退出了(独立栈资源被回收了)。
cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

__thread int number;

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
        getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());

        sleep(1);
    }

    pthread_exit((void*)6666);
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);
        tids.push_back(tid);
    }

    int cnt = 5;
    while(cnt--)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

        sleep(1);
    }

    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        void* ExitCode = nullptr;
        int n = pthread_join(tids[i], &ExitCode);
        if(n == 0)
        {
            printf("thread-%lu wait success! exitcode: %d\n", tids[i], ExitCode);
        }
        else
            break;
    }

    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

运行代码可以看到,当线程退出时其退出码就是我们设置的6666。

注意:

exit函数的作用是终止进程,任何一个线程调用exit函数也代表的是整个进程终止。

如果对主线程使用pthread_exit()函数进行终止,那么主线程会进入到僵尸状态

pthread_cancel函数

线程是可以被取消的,我们可以使用pthread_cancel函数取消某一个线程,pthread_cancel函数的函数原型如下:

cpp 复制代码
int pthread_cancel(pthread_t thread);
cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

__thread int number;

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
        getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());
    
        pthread_cancel(pthread_self());
        sleep(1);
    }

    pthread_exit((void*)6666);
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);
        tids.push_back(tid);
    }

    int cnt = 5;
    while(cnt--)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

        sleep(1);
    }

    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        void* ExitCode = nullptr;
        int n = pthread_join(tids[i], &ExitCode);
        if(n == 0)
        {
            printf("thread-%lu wait success! exitcode: %d\n", tids[i], ExitCode);
        }
        else
            break;
    }

    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

运行代码,可以看到每个线程执行一次打印操作后就退出了,其退出码不是我们设置的6666而是-1,因为我们是在线程执行pthread_exit函数前将线程取消的。

虽然线程可以自己取消自己,但一般不这样做,我们往往是用于一个线程取消另一个线程,比如主线程取消新线程。

cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

using namespace std;
#define NUM 5
#define SIZE 1024

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
        getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());

        sleep(1);
    }

    pthread_exit((void*)6666);
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);
        tids.push_back(tid);
    }

    //在主线程中取消0,1,2线程
    for(int i = 0; i < 3; i++)
    {
        pthread_cancel(tids[i]);
    }

    int cnt = 5;
    while(cnt--)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

        sleep(1);
    }

    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        void* ExitCode = nullptr;
        int n = pthread_join(tids[i], &ExitCode);
        if(n == 0)
        {
            printf("thread-%d wait success! exitcode: %d\n", i, ExitCode);
        }
        else
            break;
    }

    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

此时可以发现,0、1、2号线程退出时的退出码不是我们设置的6666,而只有未被取消的4,5号线程的退出码是6666,因为只有4,5号进程未被取消。

此外,新线程也是可以取消主线程的,例如下面我们让每一个线程都尝试对主线程进行取消。

cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

pthread_t main_pthread;

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(true)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
        getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());

        pthread_cancel(main_pthread);
        sleep(1);
    }

    pthread_exit((void*)6666);
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    main_pthread = pthread_self();

    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源
        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);
        tids.push_back(tid);
    }

    int cnt = 5;
    while(true)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());

        sleep(1);
    }

    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        void* ExitCode = nullptr;
        int n = pthread_join(tids[i], &ExitCode);
        if(n == 0)
        {
            printf("thread-%d wait success! exitcode: %d\n", i, ExitCode);
        }
        else
            break;
    }

    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

我们可以使用脚本进行查看

bash 复制代码
while :; do ps -aL | head -1 && ps -aL | grep test | grep -v grep ; echo "#######################" ; sleep 1 ; done

可以看到一段时间后,六个线程中PID和LWP相同的就是主线程,主线程右侧显示<defunct>,也就意味着主线程已经被取消了,我们也就看不到后续主线程等待新线程时打印的退出码了。

注意:

  1. 当采用这种取消方式时,主线程和各个新线程之间的地位是对等的,取消一个线程,其他线程也是能够跑完的,只不过主线程不再执行后续代码了。
  2. 我们一般都是用主线程去控制新线程,这才符合我们对线程控制的基本逻辑,虽然实验表明新线程可以取消主线程,但是并不推荐该做法。

分离线程

  • 默认情况下,新创建的线程是joinable的,线程退出后,需要对其进行pthread_join操作,否则无法释放资源,从而造成内存泄漏。
  • 但如果我们不关心线程的返回值,join也是一种负担,此时我们可以将该线程进行分离,后续当线程退出时就会自动释放线程资源。
  • 一个线程如果被分离了,这个线程依旧要使用该进程的资源,依旧在该进程内运行,甚至这个线程崩溃了一定会影响其他线程,只不过这个线程退出时不再需要主线程去join了,当这个线程退出时系统会自动回收该线程所对应的资源。
  • 可以是线程组内其他线程对目标线程进行分离,也可以是线程自己分离。
  • joinable和分离是冲突的,一个线程不能既是joinable又是分离的。

分离线程的函数叫做:pthread_detach

pthread_detach的函数原型如下:

cpp 复制代码
int pthread_detach(pthread_t thread);

参数说明:

  • thread:被分离线程的ID。

返回值说明:

  • 线程分离成功返回0,失败返回错误码。

例如,下面我们创建五个新线程后让这五个新线程将自己进行分离,那么此后主线程就不需要在对这五个新线程进行join了。

cpp 复制代码
#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <vector>

struct threadData
{
    string threadname;
    pthread_t tid;
};

string toHex(pthread_t tid)
{
    char buffer[SIZE];
    snprintf(buffer, sizeof(buffer) - 1, "0x%lx", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    threadData* td = static_cast<threadData*>(args);
    int cnt = 5;
    while(cnt--)
    {
        printf("pid: %d, ppid: %d, tid: %s %s\n",
        getpid(), getppid(), toHex(pthread_self()).c_str(), td->threadname.c_str());

        pthread_detach(pthread_self());
        sleep(1);
    }

    pthread_exit((void*)6666);
}

void InitThreadData(threadData* td, pthread_t tid)
{
    td->threadname = "thread-" + to_string(tid);
    td->tid = tid;   
}

int main()
{
    main_pthread = pthread_self();

    vector<pthread_t> tids;//进行等待线程id
    vector<threadData*> tData; //对申请的堆空间进行保存,方便后续释放

    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData* td = new threadData; //堆是所有线程共享资源

        tData.push_back(td); //将申请的空间保存起来
        pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(td));
        InitThreadData(td, tid);
        tids.push_back(tid);
    }

    while(true)
    {
        printf("main thread!!! pid: %d, ppid: %d\n", getpid(), getppid());
        //printf("[pthread_self() fetch] -> tid: %ld\n", pthread_self());
        //printf("main thread!!! [pthread_self() fetch] -> tid: %ld\n", pthread_self());

        sleep(1);
    }

    for(auto td : tData)
    {
        delete td;
    }

    return 0;
}

这五个新线程在退出时,系统会自动回收对应线程的资源,不需要主线程进行join。

线程ID及进程地址空间布局

  • pthread_create函数会产生一个线程ID,存放在第一个参数指向的地址中,该线程ID和内核中的LWP不是一回事。
  • 内核中的LWP属于进程调度的范畴,因为线程是轻量级进程,是操作系统调度器的最小单位,所以需要一个数值来唯一表示该线程。
  • pthread_create函数第一个参数指向一个虚拟内存单元,该内存单元的地址即为新创建线程的线程ID,这个ID属于NPTL线程库的范畴,线程库的后续操作就是根据该线程ID来操作线程的。
  • 线程库NPTL(Linux原生线程库)提供的pthread_self函数,获取的线程ID和pthread_create函数第一个参数获取的线程ID是一样的。

首先,我们来了解一下轻量级进程的系统调用接口clone,因为系统不让用户使用轻量级进程的调用接口,所以它被进行了封装到了线程库提供给用户使用

cpp 复制代码
#include <sched.h>
int clone(int (*fn)(void *), void *stack, int flags, void *arg, .../* pid_t *parent_tid, void *tls, pid_t *child_tid */ );

参数说明:

int (*fn)(void *) :线程需要执行的方法

void *stack : 自定义的栈

int flags : 是否和进程地址空间实现共享

Linux不提供真正的线程,只提供LWP(轻量级进程),也就意味着操作系统只需要对内核执行流LWP进行管理,而供用户使用的线程接口等其他数据,应该由线程库自己来管理,因此管理线程时的"先描述,再组织"就应该在线程库里进行。

pthread_t是什么类型?

通过ldd命令可以看到,我们采用的线程库实际上是一个动态库。

进程运行时动态库被加载到内存,然后通过页表映射到进程地址空间中的共享区,此时该进程内的所有线程都是能看到这个动态库的。

我们说每个线程都有自己私有的栈,其中主线程采用的栈是进程地址空间中原生的栈,而其余线程采用的栈就是在共享区中开辟的。除此之外,每个线程都有自己的struct pthread,当中包含了对应线程的各种属性;每个线程还有自己的线程局部存储,当中包含了对应线程被切换时的上下文数据。

每一个新线程在共享区都有这样一块区域对其进行描述,因此我们要找到一个用户级线程只需要找到该线程内存块的起始地址,然后就可以获取到该线程的各种信息。

上面我们所用的各种线程函数,本质都是在库内部对线程属性进行的各种操作,最后将要执行的代码交给对应的内核级LWP去执行就行了,也就是说线程数据的管理本质是在共享区的。

pthread_t到底是什么类型取决于实现,但是对于Linux目前实现的NPTL线程库来说,线程ID本质就是进程地址空间共享区上的一个虚拟地址,同一个进程中所有的虚拟地址都是不同的,因此可以用它来唯一区分每一个线程。

例如,我们也可以尝试按地址的形式对获取到的线程ID进行打印。

cpp 复制代码
#include <iostream>
#include <cstdio>
#include <pthread.h>

using namespace std;
#define SIZE 1024

void* threadRoutine(void* args)
{
    char* buffer = static_cast<char*>(args);
    printf("%s tid: %p\n", buffer, pthread_self());

    return nullptr;
}

int main()
{
    pthread_t tid;
    char buffer[SIZE] = "thread-1";
    int n = pthread_create(&tid, nullptr, threadRoutine, static_cast<void*>(buffer));
    if (n != 0)
    {
        perror("main::pthread_create");
        return 1;
    }

    printf("main thread tid: %p\n", pthread_self());

    pthread_join(tid, nullptr);

    return 0;
}

在此之前我们可以说这个打印结果很像一个地址,但是现在我们可以说,这本质就是一个地址

pthread_t 确切的数据类型在不同系统上可能存在差异,它可能是一个整数、结构体或者指针等。不过,你无需了解其具体的底层实现,只需把它当作一个不透明的类型来使用就可以了

相关推荐
水w1 小时前
【Python爬虫】简单案例介绍1
开发语言·爬虫·python
巨可爱熊2 小时前
高并发内存池(定长内存池基础)
linux·运维·服务器·c++·算法
zkmall2 小时前
ZKmall开源商城静态资源管理:Nginx 配置与优化
运维·nginx·开源
qq_365911603 小时前
GPT-4、Grok 3与Gemini 2.0 Pro:三大AI模型的语气、风格与能力深度对比
开发语言
yangang1854 小时前
linuxbash原理
linux·运维·服务器
小小毛桃4 小时前
在Ubuntu系统中运行Windows程序
linux·windows·ubuntu
一一Null4 小时前
关于手机取证中逻辑采集与系统备份的差异
服务器·网络·智能手机
码农新猿类4 小时前
服务器本地搭建
linux·网络·c++
Susea&5 小时前
数据结构初阶:队列
c语言·开发语言·数据结构
小度爱学习5 小时前
linux中的执行命令格式及命令帮助
linux·运维·chrome