1.线程资源回收
(1)每个线程创建后,可以由主线程调用pthread_detach()函数来让它变为unjoinable状态或者每个线程开始的时候自己调用pthread_detach(pthread_self()),这样线程在退出的时候,会自动释放自己占用的系统资源,包括线程描述符和栈等资源。
(2)通过主线程调用**pthread_join()**函数,阻塞地等待线程结束,收到线程返回值,然后释放线程资源。
(3)涉及线程函数
pthread_create()
pthread_detach()
pthread_join()
pthread_self()
(4)代码示例:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
char* thread_func1(void* arg) {
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid: %u, tid: %u (0x%x)\n", (char*)arg, (unsigned int)pid, (unsigned int)tid,
(unsigned int)tid);
char* msg = "thread_fucn1";
return msg;
}
void* thread_func2(void* arg) {
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid: %u, tid: %u (0x%x)\n", (char*)arg, (unsigned int)pid, (unsigned int)tid,
(unsigned int)tid);
char* msg = "thread_fucn2";
while (1) {
printf("%s running\n", msg);
sleep(5);
}
return NULL;
}
int main(void) {
pthread_t tid1;
pthread_t tid2;
char* ret = NULL;
if (pthread_create(&tid1, NULL, (void*)thread_func1, "thread1") != 0) {
printf("pthread_create tid1 error\n");
exit(EXIT_FAILURE);
}
if (pthread_create(&tid2, NULL, (void*)thread_func2, "thread2") != 0) {
printf("pthread_create tid2 error\n");
exit(EXIT_FAILURE);
}
pthread_detach(tid2);
pthread_join(tid1, (void*)&ret);
printf("%s return\n", ret);
sleep(5);
pthread_cancel(tid2);
printf("main thread end\n");
return 0;
}