Linux系统编程(六):线程

参考引用

1. 线程概念

1.1 什么是线程

  • 线程
    • LWP:light weight process 轻量级的进程,本质仍是进程 (在 Linux 环境下)
    • 有独立的 PCB,但没有独立的地址空间 (共享)
    • 最小的执行单位
  • 进程
    • 独立地址空间,拥有 PCB
    • 最小的资源分配单位,可看成是只有一个线程的进程
  • 进程与线程的区别
    • 在于是否共享地址空间。独居(进程);合租(线程)。Linux 下:

1.2 Linux 内核线程实现原理

  • 类 Unix 系统中,早期是没有 “线程” 概念的,80 年代才引入,借助进程机制实现出了线程的概念。因此在这类系统中,进程和线程关系密切

    • 轻量级进程 (light-weight process),也有 PCB,创建线程使用的底层函数和进程一样,都是 clone
    • 从内核里看进程和线程是一样的,都有各自不同的 PCB,但是 PCB 中指向内存资源的三级页表是相同的
    • 进程可以蜕变成线程
    • 线程可看做寄存器和栈的集合
    • 在 linux 下,线程最是小的执行单位,进程是最小的分配资源单位
  • 查看 LWP 号

    $ ps -Lf pid
    
  • 三级映射

    • 进程 PCB --> 页目录(可看成数组,首地址位于 PCB 中)–> 页表 -->物理页面 --> 内存单元
    • 对于进程来说,相同的地址 (同一个虚拟地址) 在不同的进程中,反复使用而不冲突。原因是他们虽然虚拟地址一样,但页目录、页表、物理页面各不相同。相同的虚拟地址,映射到不同的物理页面内存单元,最终访问不同的物理页面
    • 线程不同,两个线程具有各自独立的 PCB,但共享同一个页目录,也就共享同一个页表和物理页面,所以两个 PCB 共享一个地址空间
  • 实际上,无论是创建进程的 fork,还是创建线程的 pthread_create,底层实现都是调用同一个内核函数 clone

    • 如果复制对方的地址空间,那么就产出一个进程
    • 如果共享对方的地址空间,就产生一个线程
  • Linux 内核是不区分进程和线程的,只在用户层面上进行区分。线程所有操作函数 pthread_* 都是库函数

在这里插入图片描述

1.3 线程共享/非共享资源

  • 线程共享资源
    • 文件描述符表
    • 每种信号的处理方式
    • 当前工作目录
    • 用户 ID 和组 ID
    • 内存地址空间 (.text/.data/.bss/heap/共享库)
  • 线程非共享资源
    • 线程 id
    • 处理器现场和栈指针 (内核栈)
    • 独立的栈空间 (用户空间栈)
    • errno 变量
    • 信号屏蔽字
    • 调度优先级

1.4 线程优、缺点

  • 优点
    • 提高程序并发性
    • 资源开销小
    • 数据通信、共享数据方便
  • 缺点
    • 库函数,不稳定
    • 调试、编写困难、gdb 不支持
    • 对信号支持不好

优点相对突出,缺点均不是硬伤。Linux 下由于实现方法导致进程、线程差别不是很大,优先使用线程

2. 线程控制原语

2.1 pthread_self 函数

  • 获取线程 ID,其作用对应进程中 getpid() 函数
    #include <pthread.h>
    
    // 返回值 成功 0; 失败:无
    pthread_t pthread_self(void);
    // Compile and link with -pthread
    
  • 线程 ID:pthread_t 类型
    • 本质:在 Linux 下为无符号整数 (%lu),其他系统中可能是结构体实现
    • 线程 ID 是进程内部识别标志 (两个进程间,线程 ID 允许相同)

不应使用全局变量 pthread_t tid 在子线程中通过 pthread_create 传出参数来获取线程 ID,而应使用 pthread_self

2.2 pthread_create 函数

  • 创建一个新线程,其作用对应进程中的 fork() 函数

    #include <pthread.h>
    
    // 返回值 成功 0; 失败:对应的错误号
    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
    // Compile and link with -pthread
    
    • 参数 1:传出参数,保存系统分配好的线程 ID
    • 参数 2:通常传 NULL,表示使用线程默认属性。若想使用具体属性也可以修改该参数
    • 参数 3:函数指针,指向线程主函数 (线程体),该函数运行结束,则线程结束
    • 参数 4:线程主函数执行期间所使用的参数
  • 在一个线程中调用 pthread_create() 创建新的线程后,当前线程从 pthread_create() 返回继续往下执行,而新的线程所执行的代码由传给 pthread_create 的函数指针 start_routine 决定

    扫描二维码关注公众号,回复: 17001129 查看本文章
    • start_routine 函数接收一个参数,是通过 pthread_create 的 arg 参数传递给它的,该参数的类型为 void *,这个指针按什么类型解释由调用者自己定义
    • start_routine 的返回值类型也是 void *,这个指针的含义同样由调用者自己定义
    • start_routine 返回时,这个线程就退出了,其它线程可以调用 pthread_join 得到 start_routine 的返回值,类似于父进程调用 wait(2) 得到子进程的退出状态
  • pthread_create 成功返回后,新创建的线程 ID 被填写到 thread 参数所指向的内存单元

    • 进程 ID 的类型是 pid_t,每个进程的 ID 在整个系统中是唯一的,调用 getpid(2) 可以获得当前进程的 ID,是一个正整数值
    • 线程 ID 的类型是 pthread_t,它只在当前进程中保证是唯一的,在不同的系统中 pthread_t 这个类型有不同的实现,它可能是一个整数值、一个结构体、一个地址,所以不能简单地当成整数用 printf 打印,调用 pthread_self(3) 可以获得当前线程的 ID
案例 1
  • 创建一个新线程,打印线程 ID
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <errno.h>
    #include <pthread.h>
    
    void sys_err(const char *str) {
          
          
        perror(str);
        exit(1);
    }
    
    // 子线程
    void *tfn(void *arg) {
          
          
        printf("thread: pid = %d, tid = %lu\n", getpid(), pthread_self());
    
        return NULL;
    }
    
    // 主线程
    int main(int argc, char *argv[]) {
          
          
        pthread_t tid;
    
        // attr 取 NULL 表示取默认值
        int ret = pthread_create(&tid, NULL, tfn, NULL);
        if (ret != 0) {
          
          
            perror("pthread_create error");
        }
        printf("main: pid = %d, tid = %lu\n", getpid(), pthread_self());
    
        pthread_exit((void *)0);  // 等价下面两行代码,此方法更优
    
        //sleep(1);
    	//return 0;
    }
    
    # pthread 不是 Linux 下的默认的库,链接的时候无法找到 phread 库中函数的入口地址,于是链接会失败
    # 所以在 gcc 编译的时候,要加 -pthread 参数即可解决
    $ gcc pthread_create.c -o pthread_create -pthread
    $ ./pthread_create
    main: pid = 2986, tid = 140380929427264
    thread: pid = 2986, tid = 140380921087744
    
案例 2
  • 循环创建多个线程,每个线程打印自己是第几个被创建的线程
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <errno.h>
    #include <pthread.h>
    
    void sys_err(const char *str) {
          
          
    	perror(str);
    	exit(1);
    }
    
    void *tfn(void *arg) {
          
          
        // 使用 int 报错:warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
        long i = (long)arg;  // 强制类型转换
        sleep(i);
        printf("I'm %ldth thread: pid = %d, tid= %lu\n", i+1, getpid(), pthread_self());
    
        return NULL;
    }
    
    int main(int argc, char *argv[]) {
          
          
        long i;
        int ret;
        pthread_t tid;
    
        for (i = 0; i < 5; i++) {
          
          
            ret = pthread_create(&tid, NULL, tfn, (void *)i);  // i 传参采用值传递,借助强制类型转换
            if (ret != 0) {
          
          
                sys_err("pthread_create error");
            }
        }
    
        sleep(i);
        printf("I'm main, pid = %d, tid= %lu\n", getpid(), pthread_self());
    
    	return 0;
    }
    
    $ gcc pthread_more.c -o pthread_more -pthread
    $ ./pthread_more 
    I'm 1th thread: pid = 3163, tid = 139852150068992
    I'm 2th thread: pid = 3163, tid = 139852141676288
    I'm 3th thread: pid = 3163, tid = 139852133283584
    I'm 4th thread: pid = 3163, tid = 139851990673152
    I'm 5th thread: pid = 3163, tid = 139852054001408
    I'm main: pid = 3163, tid = 139852158408512
    

2.3 线程与共享

  • 线程间共享全局变量
    • 线程默认共享数据段、代码段等地址空间,常用的是全局变量。而进程不共享全局变量,只能借助 mmap
案例
  • 验证线程之间共享全局数据
    #include <stdio.h>
    #include <pthread.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    int var = 100;
    
    void *tfn(void *arg) {
          
          
        var = 200;
        printf("thread, var = %d\n", var);
        
        return NULL;
    }
    
    int main(void) {
          
          
        printf("At first var = %d\n", var);
        
        pthread_t tid;
        pthread_create(&tid, NULL, tfn, NULL);
        sleep(1);
        
        printf("after pthread_create, var = %d\n", var);
        
        return 0;
    }
    
    $ gcc ttt.c -o ttt -pthread
    $ ./ttt 
    At first var = 100
    thread, var = 200
    after pthread_create, var = 200
    

2.4 pthread_exit 函数

  • 将单个线程退出
    #include <pthread.h>
    
    void pthread_exit(void *retval);
    // Compile and link with -pthread
    
    • 参数 retval 表示线程退出状态,通常传 NULL
  • 线程中禁止使用 exit() 函数,会导致进程内所有线程全部退出
    • 取而代之使用 pthread_exit 函数,将单个线程退出
    • 任何线程里 exit 导致进程退出,其他线程未工作结束,主控线程退出时不能 return 或 exit

pthread_exit 或者 return 返回的指针所指向的内存单元必须是全局的或者是用 malloc 分配的,不能在线程函数的栈上分配,因为当其它线程得到这个返回指针时线程函数已经退出了

案例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

void sys_err(const char *str) {
    
    
	perror(str);
	exit(1);
}

void func(void) {
    
    
    pthread_exit(NULL);         // 将当前线程退出

    return ;
}

void *tfn(void *arg) {
    
    
    long i = (long)arg;         // 强制类型转换
    sleep(i);

    if (i == 2) {
    
    
        //exit(0);              // 表示退出进程
        //return NULL;          // 表示返回到调用者那里去
        //func();
        pthread_exit(NULL);     // 将当前线程退出
    }
    printf("I'm %ldth thread: pid = %d, tid= %lu\n", i+1, getpid(), pthread_self());

    return NULL;
}

int main(int argc, char *argv[]) {
    
    
    long i;
    int ret;
    pthread_t tid;

    for (i = 0; i < 5; i++) {
    
    
        ret = pthread_create(&tid, NULL, tfn, (void *)i);  // i 传参采用值传递,借助强制类型转换
        if (ret != 0) {
    
    
            sys_err("pthread_create error");
        }
    }

    sleep(i);
    printf("I'm main, pid = %d, tid= %lu\n", getpid(), pthread_self());

    return 0;
}
$ gcc pthread_exit.c -o pthread_exit -pthread
$ ./pthread_exit
I'm 1th thread: pid = 3389, tid = 140125255145216
I'm 2th thread: pid = 3389, tid = 140125246752512
I'm 4th thread: pid = 3389, tid = 140125238359808
I'm 5th thread: pid = 3389, tid = 140125229967104
I'm main: pid = 3389, tid = 140125263484736

结论

  • exit:将进程退出
  • return:返回到调用者那里去
  • pthread exit():将调用该函数的线程退出

2.5 pthread_join 函数

  • 阻塞等待线程退出(主线程等待子线程的终止),获取线程退出状态,其作用对应进程中 waitpid() 函数

    #include <pthread.h>
    
    // 返回值 成功:0  失败:错误号
    int pthread_join(pthread_t thread, void** retval);
    // Compile and link with -pthread.
    
    • thread:线程ID (不是指针)
    • retval:存储线程结束状态
      • 进程中:main 返回值、exit 参数–>int; 等待子进程结束 wait 函数参数 -->int*
      • 线程中:线程主函数返回值、pthread_exit–>void*; 等待线程结束 pthread_join 函数参数 -->void**
  • 调用该函数的线程将挂起等待,直到 id 为 thread 的线程终止。thread 线程以不同的方法终止,通过 pthread_join 得到的终止状态是不同的,总结如下

    • 如果 thread 线程通过 return 返回,retval 所指向的单元里存放的是 thread 线程函数的返回值
    • 如果 thread 线程被别的线程调用 pthread_cancel 异常终止掉,retval 所指向的单元里存放的是常数 PTHREAD_CANCELED
    • 如果 thread 线程是自己调用 pthread_exit 终止的,retval 所指向的单元存放的是传给 pthread_exit 的参数
    • 如果对 thread 线程的终止状态不感兴趣,可以传 NULL 给 retval 参数
案例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

struct thrd {
    
    
    int var;
    char str[256];
};

void sys_err(const char *str) {
    
    
	perror(str);
	exit(1);
}
/*
void *tfn(void *arg) {
    struct thrd *tval;

    tval = malloc(sizeof(tval));
    tval->var = 100;
    strcpy(tval->str, "hello thread");

    return (void *)tval;
}
*/
/*
void *tfn(void *arg) {
    // 此处 tval 为局部变量,随函数调用产生而产生,函数调用结束后栈空间就没了,对应的 tval 也没了
    struct thrd tval;              

    tval.var = 100;
    strcpy(tval.str, "hello thread");

    // 局部变量 tval 地址不可做返回值
    return (void *)&tval;
}
*/ 
void *tfn(void *arg) {
    
    
    struct thrd *tval = (struct thrd *)arg;

    tval->var = 100;
    strcpy(tval->str, "hello thread");

    return (void *)tval;
}

int main(int argc, char *argv[]) {
    
    
    pthread_t tid;

    struct thrd arg;
    struct thrd *retval;

    int ret = pthread_create(&tid, NULL, tfn, (void *)&arg);
    if (ret != 0)
        sys_err("pthread_create error");

    // tid 为传入参数,retval 为传出参数
    // 等待线程的结束,并将其返回值赋给 retval
    ret = pthread_join(tid, (void **)&retval);
    if (ret != 0)
        sys_err("pthread_join error");

    printf("child thread exit with var= %d, str= %s\n", retval->var, retval->str);
    
    pthread_exit(NULL);
}

2.5 pthread_detach 函数

  • 实现线程分离

    #include <pthread.h>
    
    int pthread_detach(pthread_t thread);
    // Compile and link with -pthread
    
  • 线程分离状态

    • 指定该状态,线程主动与主控线程断开关系。线程结束后,其退出状态不由其他线程获取,而是直接自动释放,网络、多线程服务器常用
  • 进程若有类似线程分离的机制,将不会产生僵尸进程

    • 僵尸进程产生原因:由于进程死后,大部分资源被释放,但残留资源仍存于系统中,导致内核认为该进程仍存在
  • 一般情况下,线程终止后,其终止状态一直保留到其它线程调用 pthread_join 获取它的状态为止。但是线程也可以被置为 detach 状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态

  • 不能对一个已经处于 detach 状态的线程调用 pthread_join,这样的调用将返回 EINVAL 错误。也就是说,如果已经对一个线程调用了 pthread_detach 就不能再调用 pthread_join

案例
  • 使用 pthread_detach 函数实现线程分离
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <errno.h>
    #include <pthread.h>
    
    void *tfn(void *arg) {
          
          
        printf("thread: pid = %d, tid = %lu\n", getpid(), pthread_self());
    
        return NULL;
    }
    
    int main(int argc, char *argv[]) {
          
          
        pthread_t tid;
    
        int ret = pthread_create(&tid, NULL, tfn, NULL);
        if (ret != 0) {
          
          
            fprintf(stderr, "pthread_create error: %s\n", strerror(ret));
            exit(1);
        }
        ret = pthread_detach(tid);              // 设置线程分离` 线程终止,会自动清理pcb,无需回收
        if (ret != 0) {
          
          
            fprintf(stderr, "pthread_detach error: %s\n", strerror(ret));
            exit(1);
        }
    
        sleep(1);
    
        ret = pthread_join(tid, NULL);
        if (ret != 0) {
          
          
            fprintf(stderr, "pthread_join error: %s\n", strerror(ret));
            exit(1);
        }
    
        printf("main: pid = %d, tid = %lu\n", getpid(), pthread_self());
    
        pthread_exit((void *)0);
    }
    
    $ gcc pthread_detach.c -o pthread_detach -pthread
    $ ./pthread_detach 
    thread: pid = 3684, tid = 139762658100992
    pthread_join error : Invalid argument
    

2.6 pthread_cancel 函数

  • 杀死(取消)线程,其作用,对应进程中 kill() 函数
    #include <pthread.h>
    
    int pthread_cancel(pthread_t thread);
    // Compile and link with -pthread.
    
  • 线程的取消并不是实时的,而有一定的延时,需要等待线程到达某个取消点(检查点)
    • 类似于玩游戏存档,必须到达指定的场所 (存档点,如: 客栈、仓库、城里等) 才能存储进度。杀死线程也不是立刻就能完成,必须要到达取消点
    • 取消点:是线程检查是否被取消,并按请求进行动作的一个位置
    • 可粗略认为一个系统调用 (进入内核) 即为一个取消点。如线程中没有取消点,可以通过调用 pthread_testcancel 函数自行设置一个取消点
案例
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

void *tfn1(void *arg) {
    
    
    printf("thread 1 returning\n");

    return (void *)111;    
}

void *tfn2(void *arg) {
    
    
    printf("thread 2 exiting\n");
    pthread_exit((void *)222);
}

void *tfn3(void *arg) {
    
    
    while (1) {
    
    
        pthread_testcancel();  // 自己添加取消点
    }   

    return (void *)666;
}

int main(void) {
    
    
    pthread_t tid;
    void *tret = NULL;

    pthread_create(&tid, NULL, tfn1, NULL);
    pthread_join(tid, &tret);
    printf("thread 1 exit code = %ld\n\n", (long)tret);

    pthread_create(&tid, NULL, tfn2, NULL);
    pthread_join(tid, &tret);
    printf("thread 2 exit code = %ld\n\n", (long)tret);

    pthread_create(&tid, NULL, tfn3, NULL);
    sleep(3);
    pthread_cancel(tid);
    pthread_join(tid, &tret);
    printf("thread 3 exit code = %ld\n", (long)tret);

    return 0;
}
$ gcc pthread_cancel.c -o pthread_cancel -pthread
$ ./pthread_cancel
thread 1 returning
thread 1 exit code = 111

thread 2 exiting
thread 2 exit code = 222

thread 3 exit code = -1
终止线程方式
  • 终止某个线程而不终止整个进程,有三种方法
    • 从线程主函数 return。这种方法对主控线程不适用,从 main 函数 return 相当于调用 exit
    • 一个线程可以调用 pthread_cancel 终止同一进程中的另一个线程
    • 线程可以调用 pthread_exit 终止自己

3. 线程属性

  • 之前讨论的线程都是采用线程的默认属性,默认属性已经可以解决绝大多数开发时遇到的问题。如果对程序的性能提出更高的要求那么需要设置线程属性

    • 比如可以通过设置线程栈的大小来降低内存的使用
    • 增加最大线程个数
  • 属性值不能直接设置,须使用相关函数进行操作,初始化的函数为 pthread_attr_init,这个函数必须在 pthread_create 函数之前调用,之后须用 pthread_attr_destroy 函数来释放资源

3.1 线程属性初始化

  • 应先初始化线程属性,再 pthread_create 创建线程
    #include <pthread.h>
    
    // 返回值 成功返回 0,失败返回对应的错误号
    int pthread_attr_init(pthread_attr_t *attr);     // 初始化线程属性
    int pthread_attr_destroy(pthread_attr_t *attr);  // 销毁线程属性所占用的资源
    // Compile and link with -pthread.
    

3.2 线程的分离状态

  • 线程的分离状态决定一个线程以什么样的方式来终止自己
    • 非分离状态:线程的默认属性是非分离状态,这种情况下,原有的线程等待创建的线程结束。只有当 pthread _join()函数返回时,创建的线程才算终止,才能释放自己占用的系统资源
    • 分离状态:分离线程没有被其他的线程所等待,自己运行结束了,线程也就终止了,马上释放系统资源。应该根据自己的需要,选择适当的分离状态
    #include <pthread.h>
    
    // 返回值 成功返回 0,失败返回对应的错误号
    int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);        // 设置线程属性
    int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate); // 获取线程属性
    // Compile and link with -pthread.
    
    • attr
      • 已初始化的线程属性
    • detachstate
      • PTHREAD_CREATE_DETACHED(分离线程)
      • PTHREAD_CREATE_JOINABLE(非分离线程)

3.3 线程属性控制示例

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

void *tfn(void *arg) {
    
    
    printf("thread: pid = %d, tid = %lu\n", getpid(), pthread_self());

    return NULL;
}

int main(int argc, char *argv[]) {
    
    
    pthread_t tid;
    pthread_attr_t attr;

    int ret = pthread_attr_init(&attr);
    if (ret != 0) {
    
    
        fprintf(stderr, "attr_init error:%s\n", strerror(ret));
        exit(1);
    }

    ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);      // 设置线程属性为分离属性
    if (ret != 0) {
    
    
        fprintf(stderr, "attr_setdetachstate error:%s\n", strerror(ret));
        exit(1);
    }

    ret = pthread_create(&tid, &attr, tfn, NULL);
    if (ret != 0) {
    
    
        perror("pthread_create error");
    }

    ret = pthread_attr_destroy(&attr);
    if (ret != 0) {
    
    
        fprintf(stderr, "attr_destroy error:%s\n", strerror(ret));
        exit(1);
    }

    ret = pthread_join(tid, NULL);
    if (ret != 0) {
    
    
        fprintf(stderr, "pthread_join error:%s\n", strerror(ret));
        exit(1);
    }

    printf("main: pid = %d, tid = %lu\n", getpid(), pthread_self());

    pthread_exit((void *)0);
}
$ gcc pthread_attr.c -o pthread_attr -pthread
$ ./pthread_attr 
pthread_join error:Invalid argument

3.4 线程使用注意事项

  • 主线程退出其他线程不退出,主线程应调用 pthread_exit
  • 避免僵尸线程
    • pthread join
    • pthread detach
    • pthread create 指定分离属性
    • 被 join 线程可能在 join 函数返回前就释放完自己的所有内存资源,所以不应当返回被回收线程栈中的值
  • malloc 和 mmap 申请的内存可以被其他线程释放
  • 应避免在多线程模型中调用 fork,除非马上 exec,子进程中只有调用 fork 的线程存在,其他线程在子进程中均 pthread_exit
  • 信号的复杂语义很难和多线程共存,应避免在多线程引入信号机制

猜你喜欢

转载自blog.csdn.net/qq_42994487/article/details/133350868
今日推荐