【Linux】线程控制
创始人
2024-05-10 19:55:24

目录

  • 🌈前言
  • 🌸1、Linux线程控制
    • 🍡1.1、创建线程(pthread_create)
    • 🍢1.2、通过指令查看线程PID和LWP
    • 🍧1.3、获取线程ID(pthread_self)
    • 🍨1.4、线程终止(pthread_exit/cancel)
    • 🍨1.5、线程等待(pthread_join)
    • 🍱1.6、分离线程(pthread_detach)

🌈前言

这篇文章给大家带来线程控制的学习!!!


🌸1、Linux线程控制

POSIX线程库(第三方库)
  • 这是Linux自带原生库,定义了创建和操纵线程的一套API(函数接口),绝大多数函数的名字都是以“pthread_”为前缀
  • 要使用这些函数库,要通过引入头文
  • 链接这些线程函数库时要使用编译器命令的“-lpthread”选项,因为它是第三方库
  • 任何语言在Linux想要实现一套自己的线程库,都是封装POSIX线程库来实现的

🍡1.1、创建线程(pthread_create)

#include 
typedef unsigned long int pthread_t;int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
函数解析
  • 作用:pthread_create()函数在调用过程中启动一个新线程
  • thread:该参数返回一个线程ID输出型参数,由0S填充
  • attr:该参数是用于设置线程的属性,如果为,则设置线程默认的属性,返回值void*可以指定线程退出状态值
  • start_routine:该参数是一个回调函数线程启动后,会执行该函数的代码
  • arg:该参数是用来命名线程的,它会被传给线程启动函数的参数(start_routine
  • 返回值:启动成功返回0,启动失败返回错误码(线程有自己的错误码)

创建一个线程,并且让它跑起来

#include 
#include 
#include 
#include 
using namespace std;// |---------------------------------------------------------------------|
// | #include                                                 |
// | int pthread_create(pthread_t *thread, const pthread_attr_t *attr,   |
// |                     void *(*start_routine) (void *), void *arg);    |
// |---------------------------------------------------------------------|void *CallPthread1(void *arg)
{printf("I am %s\n", (const char *)arg);// 指定线程退出状态值return (void *)0;
}void *CallPthread2(void *arg)
{printf("I am %s\n", (const char *)arg);// 指定线程退出状态值return (void *)0;
}int main()
{// 1、定义线程id,该id由OS填充pthread_t tid1;pthread_t tid2;// 创建线程,并且填充t1的id,arg参数给线程命名,并且让线程执行CallPthread代码if (pthread_create(&tid1, nullptr, CallPthread1, (void *)"thread t1") != 0){exit(EXIT_FAILURE);}if (pthread_create(&tid2, nullptr, CallPthread2, (void *)"thread t2") != 0){exit(EXIT_FAILURE);}return 0;
}

运行结果:

[lyh@192 Make_thread(1)]$ ./Thread_Creation 
I am thread t1
I am thread t2

错误检查
  • 传统的一些库函数是:成功返回0,失败返回-1,并且对全局变量errno赋值以指示错误
  • 线程函数出错时,不会设置全局变量errno(但是大部分其他库函数会设置),而是通过函数的返回值错误码返回
  • 线程同样也提供了线程内的errno变量每个线程都有属于自己的局部errno,以避免一个线程干扰另一个线程
  • 对于线程函数的错误,建议通过返回值来判定,因为读取返回值要比读取线程内的errno变量开销更小

🍢1.2、通过指令查看线程PID和LWP

前言
  • 线程是进程的执行程序(执行流),它们的PID是一样的
  • 但是,进程和轻量级进程(线程)ID(LWP)是不一样的
  • 轻量级进程(线程)是CPU调度基本单位,需要一个唯一的数值(LWP)来标识它
  • 我们可以通过ps -aL查看全部正在运行主线程(main函数)新线程(pthread_create)的信息
#include 
#include 
#include 
#include 
using namespace std;// |---------------------------------------------------------------------|
// | #include                                                 |
// | int pthread_create(pthread_t *thread, const pthread_attr_t *attr,   |
// |                     void *(*start_routine) (void *), void *arg);    |
// |---------------------------------------------------------------------|void *CallPthread1(void *arg)
{printf("I am %s, thread PID: %d\n", (const char *)arg, getpid());sleep(3);// 指定线程退出状态值return (void *)0;
}void *CallPthread2(void *arg)
{printf("I am %s, thread PID: %d\n", (const char *)arg, getpid());sleep(3);// 指定线程退出状态值return (void *)0;
}int main()
{// 1、定义线程id,该id由OS填充pthread_t tid1;pthread_t tid2;// 创建线程,并且填充t1的id,arg参数给线程命名,并且让线程执行CallPthread代码if (pthread_create(&tid1, nullptr, CallPthread1, (void *)"thread t1") != 0){exit(EXIT_FAILURE);}if (pthread_create(&tid2, nullptr, CallPthread2, (void *)"thread t2") != 0){exit(EXIT_FAILURE);}while (true){cout << "我是主线程, pid: : " << getpid() << endl;sleep(1);}return 0;
}

在这里插入图片描述


🍧1.3、获取线程ID(pthread_self)

线程ID
  • pthread_ create函数会产生一个线程ID,存放在第一个参数指向的地址中。该线程ID和前面说的线程ID不是一回事
  • 前面讲的线程ID属于进程调度的范畴。因为线程是轻量级进程,是操作系统调度器的最小单位,所以需要一个数值来唯一表示该线程
  • pthread_ create函数第一个参数指向一个虚拟内存单元,该内存单元的地址即为新创建线程的线程ID,属于NPTL线程库的范畴
  • 线程库的后续操作,就是根据该线程ID来操作线程的

线程库NPTL提供了pthread_ self函数,可以获得线程自身的ID:

#include 
typedef unsigned long int pthread_t;pthread_t pthread_self(void);
函数解析
  • 作用:获取线程自身的ID
  • 返回值:此函数一定会调用成功,返回调用线程的ID
#include 
#include 
#include 
#include 
using namespace std;void *CallPthread1(void *arg)
{// 获取线程idpthread_t id = pthread_self();printf("I am %s, pthread PID: %u\n", (const char *)arg, id);// 指定线程退出状态值return (void *)0;
}void *CallPthread2(void *arg)
{// 获取线程idpthread_t id = pthread_self();printf("I am %s, pthread PID: %u\n", (const char *)arg, id);// 指定线程退出状态值return (void *)0;
}int main()
{// 1、定义线程id,该id由OS填充pthread_t tid1;pthread_t tid2;// 创建线程,并且填充t1的id,arg参数给线程命名,并且让线程执行CallPthread代码if (pthread_create(&tid1, nullptr, CallPthread1, (void *)"thread t1") != 0){exit(EXIT_FAILURE);}if (pthread_create(&tid2, nullptr, CallPthread2, (void *)"thread t2") != 0){exit(EXIT_FAILURE);}return 0;
}

运行结果:

[lyh@192 Make_thread(1)]$ ./Thread_Creation 
I am thread t1, pthread PID: 3796985600
I am thread t2, pthread PID: 3788592896

🍨1.4、线程终止(pthread_exit/cancel)

如果需要只终止某个线程而不终止整个进程

三种方法
  • 线程函数return。这种方法对主线程不适用,从main函数return相当于调用exit
  • 线程可以调用pthread_ exit函数终止自己
  • 一个线程可以调用pthread_ cancel函数终止同一进程中的另一个线程

pthread_exit函数:

 #include 
typedef unsigned long int pthread_t;void pthread_exit(void *value_ptr);
函数解析
  • 作用:pthread_exit()函数终止调用线程,就如同进程在结束时调用exit函数一样
  • 返回值:无返回值,此函数一定会调用成功
  • value_ptr:保存线程退出后的返回值,返回一个指向某个对象的指针,该指针不能是线程栈局部变量,后面线程等待可以获取到这个变量
  • 需要注意:pthread_exit或者return返回的指针所指向的内存单元必须是全局的或者是用malloc分配的,不能在线程函数的栈上分配,因为当其它线程得到这个返回指针时线程函数已经退出了
#include 
#include 
#include 
#include 
using namespace std;void *CallPthread1(void *arg)
{// 获取线程idpthread_t id = pthread_self();printf("I am %s, pthread PID: %u\n", (const char *)arg, id);// 线程终止,线程退出后的值设为空pthread_exit(nullptr);
}void *CallPthread2(void *arg)
{// 获取线程idpthread_t id = pthread_self();printf("I am %s, pthread PID: %u\n", (const char *)arg, id);pthread_exit(nullptr);
}int main()
{// 1、定义线程id,该id由OS填充pthread_t tid1;pthread_t tid2;// 创建线程,并且填充t1的id,arg参数给线程命名,并且让线程执行CallPthread代码if (pthread_create(&tid1, nullptr, CallPthread1, (void *)"thread t1") != 0){exit(EXIT_FAILURE);}if (pthread_create(&tid2, nullptr, CallPthread2, (void *)"thread t2") != 0){exit(EXIT_FAILURE);}return 0;
}

pthread_cancel函数:

 #include 
typedef unsigned long int pthread_t;int pthread_cancel(pthread_t thread);
函数解析
  • 作用:pthread_cancel函数向进程中正在运行的线程发送取消请求
  • 返回值:成功返回0,失败返回一个errno错误码
  • thread:线程ID(pthread_create中第一个输出型参数的值)
#include 
#include 
#include 
#include 
using namespace std;void *CallPthread1(void *arg)
{// 获取线程idpthread_t id = pthread_self();while (true){printf("I am %s, pthread PID: %u\n", (const char *)arg, id);sleep(1);}pthread_exit(nullptr);
}void *CallPthread2(void *arg)
{// 获取线程idpthread_t id = pthread_self();while (true){printf("I am %s, pthread PID: %u\n\n", (const char *)arg, id);sleep(1);}pthread_exit(nullptr);
}int main()
{// 1、定义线程id,该id由OS填充pthread_t tid1;pthread_t tid2;// 创建线程,并且填充t1的id,arg参数给线程命名,并且让线程执行CallPthread代码if (pthread_create(&tid1, nullptr, CallPthread1, (void *)"thread t1") != 0){exit(EXIT_FAILURE);}if (pthread_create(&tid2, nullptr, CallPthread2, (void *)"thread t2") != 0){exit(EXIT_FAILURE);}// 二秒后退出ID为tid1的线程sleep(2);pthread_cancel(tid1);return 0;
}

运行结果:

在这里插入图片描述


🍨1.5、线程等待(pthread_join)

为什么需要线程等待?
  • 已经退出的线程,其空间没有被释放,仍然在进程的地址空间内
  • 创建新的线程不会复用刚才退出线程的地址空间
 #include 
typedef unsigned long int pthread_t;int pthread_join(pthread_t thread, void **value_ptr);
函数解析
  • 作用:pthread_join函数等待指定的线程终止,如果该线程已经终止,则pthread_join()立即返回
  • 返回值:成功返回0,失败返回一个errno错误码
  • thread:线程ID(pthread_create中第一个输出型参数的值)
  • value_ptr:它指向一个指针,这个指针(解引用value_ptr)指向线程的返回值
#include 
#include 
#include 
#include 
using namespace std;void *CallPthread1(void *arg)
{// 获取线程idpthread_t id = pthread_self();printf("I am %s, pthread PID: %u\n", (const char *)arg, id);// p是一个线程状态返回值,传给pthread_exit参数const char* p = "线程退出成功1! ! !";pthread_exit((void*)p);
}void *CallPthread2(void *arg)
{// 获取线程idpthread_t id = pthread_self();printf("I am %s, pthread PID: %u\n", (const char *)arg, id);const char* p = "线程退出成功2! ! !";pthread_exit((void*)p);
}int main()
{// 1、定义线程id,该id由OS填充pthread_t tid1;pthread_t tid2;// 创建线程,并且填充t1的id,arg参数给线程命名,并且让线程执行CallPthread代码if (pthread_create(&tid1, nullptr, CallPthread1, (void *)"thread t1") != 0){exit(EXIT_FAILURE);}if (pthread_create(&tid2, nullptr, CallPthread2, (void *)"thread t2") != 0){exit(EXIT_FAILURE);}void* RV1;void* RV2;// 等待线程退出,并且获取线程退出时的返回值pthread_join(tid1, &RV1);pthread_join(tid2, &RV2);cout << (const char*)RV1 << endl;cout << (const char*)RV2 << endl;return 0;
}

运行结果:

[lyh@192 Make_thread(1)]$ make
g++ -o Thread_Creation Thread_Creation.cpp -std=c++11 -lpthread[lyh@192 Make_thread(1)]$ ./Thread_Creation 
I am thread t1, pthread PID: 2257434368
I am thread t2, pthread PID: 2249041664
线程退出成功1! ! !
线程退出成功2! ! !

  • 调用该函数的线程将挂起等待,直到id为thread的线程终止

  • thread线程以不同的方法终止,通pthread_join得到的终止状态是不同的

总结
  • 如果thread线程通过return返回,value_ ptr所指向的内存单元里存放的是thread线程函数的返回值
  • 如果thread线程被别的线程调用pthread_ cancel异常终止,value_ ptr所指向的单元里存放的是v常数PTHREAD_ CANCELED
  • 如果thread线程是自己调用pthread_exit终止的,value_ptr所指向的单元存放的是传给pthread_exit的参数
  • 如果对thread线程的终止状态不感兴趣,可以传NULL给value_ ptr参数

在这里插入图片描述


🍱1.6、分离线程(pthread_detach)

概念
  • 默认情况下,新创建的线程是joinable(连接的)的,线程退出后,需要对其进行pthread_join操作,否则无法释放资源,从而造成系统泄漏
  • 如果不关心线程的返回值join是一种负担,这个时候,我们可以告诉系统,当线程退出时,自动释放线程资源
 #include 
typedef unsigned long int pthread_t;int pthread_detach(pthread_t thread);
函数解析
  • 作用:pthread_detach函数可以让主线程和线程进行分离,线程自动释放资源
  • 返回值:成功返回0,失败返回一个errno错误码
  • thread:线程ID(pthread_create中第一个输出型参数的值)
注意
  • 可以是线程组内其他线程对目标线程进行分离,也可以是线程自己分离
  • joinable(连接)和分离是冲突的,一个线程不能既是joinable又是分离的

相关内容

热门资讯

阿西吧是什么意思 阿西吧相当于... 即使你没有受到过任何外语培训,你也懂四国语言。汉语:你好英语:Shit韩语:阿西吧(아,씨발! )日...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
demo什么意思 demo版本... 618快到了,各位的小金库大概也在准备开闸放水了吧。没有小金库的,也该向老婆撒娇卖萌服个软了,一切只...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...