前言
我们在上一篇博客中学习了单线程的基本控制,及创建、阻塞、终止等操作,这篇博客介绍多个线程的控制。
一、线程函数的认识
1、基本函数的回顾
1、线程的创建pthread_create
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
2、线程阻塞pthread_join
int pthread_join(pthread_t thread, void **retval);
3、线程退出pthread_exit
void pthread_exit(void *retval);
2、线程的分离pthread_detach
int pthread_detach(pthread_t thread);
- 参数说明:
thread
:要分离的线程的标识符。
- 返回值:
- 成功时返回 0。
- 出错时返回错误码,可通过
perror
函数输出错误信息。
- 含义
- 当一个线程被创建时,它的状态默认是可连接的(joinable),这意味着另一个线程可以使用
pthread_join
函数来等待它的结束,并获取其返回值。而线程分离是将线程的状态设置为已分离(detached),这样就不需要其他线程来等待它结束,当线程结束时,其资源会自动被系统回收。 - 分离的线程在结束时会自动释放资源,包括线程的堆栈和其他系统资源,而不需要主线程或其他线程调用
pthread_join
函数来回收。 - 对于一些后台线程,例如日志记录线程、垃圾回收线程等,它们通常在程序的整个生命周期内持续运行,并且不需要主线程等待它们结束或获取它们的返回值。将这些线程设置为分离状态可以简化线程的管理,避免主线程在结束时因为没有调用
pthread_join
而产生资源泄漏。
- 当一个线程被创建时,它的状态默认是可连接的(joinable),这意味着另一个线程可以使用
通俗的说就是当我们主线程不需要等待子线程的返回值时,我们可以让主线程与次线程分离开,不让主线程等待子线程的退出。
代码样例
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <string>
using namespace std;
#define NUM 4
void *Threadroutine(void *args)
{
int cnt = 0;
while (true)
{
cout << (*((string *)args)).c_str() << endl;
sleep(1);
if ((cnt++) == 3)
{
break;
}
}
cout<<(*((string *)args)).c_str()<<"运行完了"<<endl;
return nullptr;
}
int main()
{
vector<pthread_t> tids;
for (int i = 0; i < NUM; i++)
{
string *name = new string("我是线程-" + to_string(i));
pthread_t tid;
tids.push_back(tid);
pthread_create(&tids[i], nullptr, Threadroutine, name);
}
for (auto &