关于线程的创建、终止和线程泄露讨论
使用线程的pthread相关函数时,需要加入头文件#include<pthread.h>,并在gcc编译时指定线程库-pthread 或 -lpthread
1.线程创建
int pthread_create(pthread_t * tid,pthread_attr_t * attr,void * (* start_routine)(viod *),void * arg);
tid是用于获取创建的线程id
attr是线程属性,通常置NULL
start_routine是线程入口函数
arg是通过线程入口函数给线程传递的参数
成功返回0,失败返回非0
2.线程终止(退出线程)
(1).线程入口函数中执行return
(2).使用库函数 pthread_exit(void * retal); retal是线程的返回值。可任意位置调用此函数,哪个线程调用,就会退出哪个线程;
(3).使用库函数 int pthread_cancel(pthread_t tid); tid为一个指定线程的id,指定哪个线程就退出哪个线程。
3.线程泄露
线程在默认情况下,线程退出也不会回收资源,容易产生线程泄露,避免线程泄露有如下两种方法。
(1). pthread_join() 主线程等待子线程
#include <pthread.h>
#include <stdio.h>
void* test_fun(void* arg)
{
printf("test_fun pthread create!!!\n");
return 0;
}
int main()
{
pthread_t test_id;
pthread_create(&test_id, NULL, test_fun, NULL); // 主线程里开启子线程
pthread_join(test_id, NULL); // 主线程等待子线程 t 的结束
return 0;
}
(2).pthread_detach() 子线程主动脱离主线程
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* test_fun(void* arg)
{
pthread_detach(pthread_self()); // 子线程主动 detach
printf("test_fun pthread create\n");
return 0;
}
int main()
{
pthread_t test_id;
pthread_create(&test_id, NULL, test_fun, NULL); // 主线程里开启子线程test_fun
sleep(1);
return 0;
}