学习《POSIX多线程程序设计》笔记一(分离线程)

//以下程序在linux  系统亲测通过
//gcc detachstate_pthread.c  -o detachstate_pthread -lpthread
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

void thread_routine (void)
{
    int i =0;
    for(i=0;i<10;i++)
    {
        printf(" i :%d  \n",i);
        sleep(2);
    }
    pthread_exit("");
}

void thread_routine_one (void)
{
    int i =0;
    for(i=0;i<15;i++)
    {
        printf("ii: %d  \n",i);
        sleep(2);
    }
    pthread_exit("");
}

int main (int argc, char *argv[])
{
    pthread_t thread_id ,thread_id2;
    void *thread_result;
    int status;
    //创建成功返回0 //并开始运行 thread_routine
    status = pthread_create (&thread_id, NULL, (void *)thread_routine, NULL);
    if (status == 0)
    {
        printf("Create thread %d\n",thread_id);
    }
     status = pthread_create (&thread_id2, NULL, (void *)thread_routine_one, NULL);
    if (status == 0)
    {
        printf("Create thread %d\n",thread_id2);
    }
    //正常状态:可以由其他线程终止,回收资源。(可以看成有人等,有人陪)
    //分离状态:不能被其他线程终止,存储资源在它终止时由系统自动回收释放。(没人等,没人陪,自生自灭,死后回归大自然)
    //设置为分离线程 //这是创建成功后设置为分离线程 //还有一种创建的时候就设置为分离状态
    pthread_detach(thread_id);
    pthread_detach(thread_id2);
    //另一种创建分离线程的方向 在下面

    printf("不需要等待了,直接运行");
    sleep(10);
    return 0;
}

/*

创建 detach 线程的另外一种方式:

pthread_t tid;

pthread_attr_t attr;

pthread_attr_init(&attr);

pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

pthread_create(&tid, &attr, THREAD_FUNCTION, arg);

总之为了在使用 pthread 时避免线程的资源在线程结束时不能得到正确释放,
从而避免产生潜在的内存泄漏问题,在对待线程结束时,要确保该线程处于 detached 状态,
否着就需要调用 pthread_join() 函数来对其进行资源回收。

*/







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值