linux创建线程时,需注意线程内存回收问题!

有三种方法可以回收线程内存

1.设置线程属性

 

    pthread_attr_t p_pth_attr;

 

    if  (0 != pthread_attr_init(&p_pth_attr))                                    
    {
        perror("pthread_attr_init");
        return -1;
    }

    if  (0 != pthread_attr_setdetachstate(&p_pth_attr, PTHREAD_CREATE_DETACHED))  
    {//此处设置成分离线程内存,一旦线程结束,立刻回收内存
        perror("pthread_attr_setdetachstate");
        return -1;
    }

2.在创建线程后调用pthread_join ()

 

3.使用pthread_detach()

 

void *ThreadFunc()

{

    static int count = 1;

    printf ("Create thread %d/n", count);

    pthread_detach (pthread_self());

    count++;

 

}

 

具体方法,参见http://blog.sina.com.cn/s/blog_4b9216f50100cwtc.html

 

以上只要使用一种方法即可,不可多种同时使用

The pthread_detach () function indicates that system resources for the specified thread should be reclaimed when the thread ends. If the thread is already ended, resources are reclaimed immediately. This routine does not cause the thread to end. After pthread_detach () has been issued, it is not valid to try to pthread_join () with the target thread.

Eventually, you should call pthread_join () or pthread_detach () for every thread that is created joinable (with a detachstate of PTHREAD_CREATE_JOINABLE ) so that the system can reclaim all resources associated with the thread. Failure to join to or detach joinable threads will result in memory and other resource leaks until the process ends.

 

具体说明,参见http://www.cnblogs.com/cy163/archive/2008/08/17/1269923.html

### Linux 线程创建回收的性能开销 在Linux环境中,线程作为轻量级进程存在,其创建和销毁操作相较于传统进程更加高效。然而,在高并发场景下,频繁创建和销毁线程仍然会产生显著的性能开销。 #### 创建线程的性能开销 当调用`pthread_create()`函数来启动一个新的线程,内核需要执行一系列初始化工作,包括但不限于: - 分配栈空间给新线程; - 初始化线程控制块(TCB),记录线程状态和其他必要信息; - 设置上下文环境以便于调度器管理; 这些准备工作虽然相对简单快速,但在极高频率的操作中累积起来也会成为瓶颈[^1]。 对于多处理器或多核心系统而言,如果应用程序能够有效地利用硬件资源,则可以减轻部分因线程创建所带来的负担。但是需要注意的是,过度依赖增加线程数量可能会导致竞争条件加剧以及缓存失效等问题的发生[^2]。 #### 回收线程的性能开销 在线程完成任务之后,通常有两种方式处理该线程:等待它自然终止并通过`pthread_join()`收集返回值;或者将其标记为可分离(separable),让操作系统自动清理不再使用的资源。前者涉及到阻塞当前执行路径直到目标线程结束,而后者则可能造成僵尸线程(zombie thread)现象——即已经退出但尚未被父进程释放的相关结构体仍占用着少量内存区域。 无论是哪种情况,都不可避免地会消耗一定的CPU周期用于管理和协调各个活动单元之间的关系变化过程。特别是在大规模并行计算场合里,不当的设计模式很容易引发严重的效率损失甚至死锁状况出现。 ### 性能优化建议 为了降低上述提到的各种潜在负面影响,并提高整体运行效能,可以从以下几个方面入手进行针对性改进措施: - **合理规划线程池大小**: 预先设定好固定数目的一组工作者线程(workers threads),按需分配具体工作任务而不是临新建实例对象。这样既能保证响应速度又能有效防止无谓的增长趋势。 - **采用异步I/O模型**: 对于涉及大量磁盘读写或网络通信的应用程序来说,应该尽可能多地采纳非阻塞性设计思路,使得单个线程能够在等待外部事件的同继续从事其他有意义的工作项。 - **调整优先级策略**: 根据实际业务逻辑需求灵活配置不同类别作业的重要性级别,确保关键流程获得足够的计算能力支持而不至于受到次要因素干扰影响进度安排。 - **优化同步机制**: 尽量减少临界区(critical section)范围内的争用程度,推广使用细粒度加锁(locking at finer granularity)技术手段以提升吞吐率表现水平。 - **考虑NUMA架构特性**: 如果服务器平台具备Non-uniform Memory Access (NUMA) 特征的话,那么应当特别关注如何使各子系统的交互更为顺畅和谐,比如通过绑定特定物理位置上的CPU核心集簇去专门负责某些类型的负载请求等办法实现局部最优解方案的选择[^3]. ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> void *thread_function(void *arg){ printf("Thread is running\n"); sleep(1); pthread_exit(NULL); // Properly exit the thread to avoid zombie state. } int main(){ pthread_t tid; int ret; ret = pthread_create(&tid, NULL, thread_function, NULL); if(ret != 0){ perror("Failed to create thread"); exit(EXIT_FAILURE); } void* res; ret = pthread_join(tid,&res); // Wait for the created thread and collect its result. if(ret != 0){ perror("Failed to join with thread"); exit(EXIT_FAILURE); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值