linux小实验(1)---线程

本文探讨了线程生命周期及创建机制,通过两个实例展示了线程如何随进程或独立于进程运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)、线程会随创建它的进程死掉而死掉

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h>

void *thread(void *);

int main() 
{ 
    pthread_t t_a; 
    pthread_t t_b; 

    pthread_create(&t_a,NULL,thread,(void *)1);
    pthread_create(&t_b,NULL,thread,(void *)2);
    printf("main process is teminated!\n");
    exit(0); 
} 

void *thread(void *junk)
{ 
    int i=1;

    for(i=1;i<=4;i++)
    { 
        printf("thread %d ...\n",(int)junk);
        sleep(1);
   }
   pthread_exit(0);
}


(2)、线程不会随创建它的线程死掉而死掉

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h>

void *thread_parent(void *);
void *thread_child(void *);

int main() 
{ 
    pthread_t t;
    void* ret;

    pthread_create(&t,NULL,thread_parent,(void *)0);

    pthread_join(t,&ret);
    printf("parent thread process is terminated.\n");

    sleep(10);

    printf("main process is teminated!\n");
    exit(0);

}

void *thread_parent(void *para)
{
    pthread_t t1,t2;

    pthread_create(&t1,NULL,thread_child,(void *)1);
    pthread_create(&t2,NULL,thread_child,(void *)2);
    pthread_exit(0);
}

void *thread_child(void *para)
{ 
    int i=1;
    for(i=1;i<=4;i++)
    { 
        printf("child thread %d...\n",(int)para);
        sleep(1);
    }
    printf("child thread %d t is terminated!\n",(int)para);
    pthread_exit(0);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值