Linux下多线程的创建和控制
2026-02-08
运维
00
请注意,本文编写于 55 天前,最后修改于 5 天前,其中某些信息可能已经过时。

目录

原理(常用函数)
1、Pthread_create函数
函数原型:
参数
2、Pthread_join函数
函数原型
参数
3、pthread_self函数
函数原型
4、Pthreadkeycreate函数
函数原型
参数
5、pthreadkeydelete函数
函数原型
6、pthread_setspecific函数
函数原型
参数
7、pthread_getspecific函数
函数原型
参数
示例
在main函数中创建两个子线程,两个子线程的函数为child1和child2

原理(常用函数)

1**、Pthread_create函数**

​ 创建一个新 的线程,其功能对应进程中的fork函数,如果成功返回0,不成功返回一个错误的号码

函数原型:

展开代码
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

参数

  • pthread_t *thread:这是一个指向pthread_t类型变量的指针,用于存储新创建的线程的标识符。当函数成功时,这个变量会被设置为新线程的线程 ID。
  • const pthread_attr_t *attr:这是一个指向const pthread_attr_t结构的指针,用于设置线程的属性。如果你不需要设置特殊的属性,可以传递NULL。
  • void *(*start_routine) (void *):这是一个指向函数的指针,该函数将成为新线程的入口点。这个函数应该接受一个void指针作为参数,并返回一个void指针。通常,这个函数不会返回任何值,但在某些情况下,它可能用于线程间的通信。当指定的函数运行完后,则线程就结束了。
  • void *arg:设置线程主函数的参数,如果没有,这设置为NULL。你可以通过这个参数向新线程传递数据。

2**、Pthread_join函数**

​ 等待执行的线程,并接受子进程返回的状态

函数原型

展开代码
int pthread_join(pthread_t thread, void **retval);

参数

  • pthread_t thread:这是要等待的线程的标识符。这个标识符通常是在调用 pthread_create 函数时返回的。
  • void **retval:这是一个指向指针的指针,用于接收子线程的返回值。如果不需要子线程的返回值,可以将这个参数设置为 NULL。

3、pthread_self****函数

​ 获取当前线程的id,其返回值为Pthread_t类型(线程id类型)

函数原型

展开代码
pthread_t pthread_self(void);

4、Pthread_key_create****函数

​ 创建线程私有数据pthread_key_t结构

函数原型

展开代码
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));

参数

  • pthread_key_t *key:这是一个指向pthread_key_t类型变量的指针,用于存储新创建的键。在成功调用pthread_key_create后,这个变量将包含新键的标识符。
  • void (*destructor)(void*):这是一个函数指针,指向一个析构函数。析构函数在线程退出时自动调用,用于释放与键关联的数据。如果不需要析构函数,可以将此参数设置为NULL。

​ 注意:此处的pthread_key_t结构,可以理解为各个线性中,同名但内容不同的变量

5、pthread_key_delete函数

​ 注销线程中的私有数据

函数原型

展开代码
int pthread_key_delete(pthread_key_t key);

6、pthread_setspecific函数

​ 写线程私有数据

函数原型

展开代码
int pthread_setspecific(pthread_key_t key, const void *value);

参数

  • pthread_key_t key:这是通过pthread_key_create函数创建的线程特定数据键。
  • const void *value:这是要与键相关联的值。这个值可以是任何类型的数据,因为void *是一个通用指针类型。

7、pthread_getspecific函数

​ 读线程私有数据

函数原型

展开代码
void *pthread_getspecific(pthread_key_t key);

参数

  • 第一个参数为指定需要内容的****pthread_key_t变量。此处需要注意,如果pthread_key_t变量的内容为空,则会返回0(NULL)

示例

在main函数中创建两个子线程,两个子线程的函数为child1和child2

展开代码
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void* child1(){ printf("Child 1 is running\n"); pthread_exit(NULL); } void* child2(){ printf("Child 2 is running\n"); pthread_exit(NULL); } int main() { printf("this is main thread\n"); pthread_t tid1, tid2; int ret; ret = pthread_create(&tid1, NULL, child1, NULL); if (ret != 0) { printf("Error creating tid 1\n"); exit(EXIT_FAILURE); } ret = pthread_create(&tid2, NULL, child2, NULL); if (ret != 0) { printf("Error creating tid 2\n"); exit(EXIT_FAILURE); } pthread_join(tid1, NULL); pthread_join(tid2, NULL); return 0; }

本文作者:zzz

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!