04-基础篇-关于线程的创建、终止和线程泄露讨论

 

关于线程的创建、终止和线程泄露讨论

使用线程的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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值