c多线程编程

该博客介绍了使用pthread库在C语言中创建和销毁线程的方法,包括示例代码展示了如何创建并行执行的两个线程,以及三种线程销毁的方式:初始化属性设置为分离状态、detach函数和使用join阻塞等待线程退出。
摘要由CSDN通过智能技术生成

#include <pthread.h>
void *testThread(){
    printf("Hello, World!New Thread11\n");
}
void *testThread2(){
    printf("Hello, World!New Thread22\n");
}
int main() {
    printf("Hello, World!\n");
    pthread_t pthread_t,pthread_t2;
    pthread_create(&pthread_t, NULL, testThread, NULL);
    pthread_create(&pthread_t2, NULL, testThread2, NULL);
    pthread_detach(&pthread_t);
    pthread_detach(&pthread_t2);
    return 0;
}

输出:

Hello, World!

Hello, World!New Thread11

Hello, World!New Thread22

//销毁线程的3种方法
//方法一
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ret = pthread_create(&pid, &attr, __task, NULL); 

//方法二
pthread_detach(pid);
pthread_detach(pthread_self());

//方法三 阻塞等待线程退出(线程内部必须有退出的变量等标识)
pthread_join(pid, NULL);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值