linux下编写一个简单的线程

本文介绍Linux下创建、退出及等待线程的处理函数,并通过一个具体示例展示了如何使用这些函数来创建和管理线程。

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

linux下线程相关处理函数如下:

-----创建线程

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,

                          void *(*start_routine) (void *), void *arg);

thread:若创建成功则保存被创建线程的线程句柄;

attr:线程属性;

start_routine:线程处理函数;

arg:线程处理函数参数;

返回值:0 创建成功  非零  创建失败


-----退出当前线程

void pthread_exit(void *retval);

retval:退出参数


-----等待某一线程退出

等待某一指定的线程退出,若未退出则阻塞

int pthread_join(pthread_t thread, void **retval);

thread:被等待退出的线程句柄;

retval:保存退出参数;

返回值:0  成功  非零表示失败


例程:

创建一个线程周期打印10次自己的线程句柄。主线程在创建线程后也周期打印5次自己的线程句柄,打印结束后等待子线程结束。

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

void* pthread_function(void *arg)
{
        int i;
        /*  子线程打印10次线程句柄  */
        for(i=0; i<10; i++) {
                printf("%lu:This is a new pthread:%d\n", pthread_self(), i);
                sleep(1);
        }

        pthread_exit(NULL);

        return NULL;
}

int main(void)
{
        pthread_t threadid;
        int i;

        printf("%lu:create a new pthread\n", pthread_self());
        /*  创建线程  */
        if( pthread_create(&threadid, NULL, pthread_function, NULL) != 0 ) {
                perror("pthread create");
                exit(-1);
        }
        printf("%lu:create success:%lu\n", pthread_self(), threadid);

        /*  主线程打印5次线程句柄  */
        for(i=0; i<5; i++) {
                printf("%lu:father:%d\n", pthread_self(), i);
                sleep(1);
        }
        /*  等待子线程结束  */
        printf("%lu:wait the new pthread\n", pthread_self());
        if( pthread_join(threadid, NULL) != 0) {
                perror("pthread join");
                exit(-1);
        }

        printf("%lu:over\n", pthread_self());

        return 0;
}

结果如下:

3075774208:create a new pthread
3075774208:create success:3075771200
3075774208:father:0
3075771200:This is a new pthread:0
3075774208:father:1
3075771200:This is a new pthread:1
3075774208:father:2
3075771200:This is a new pthread:2
3075774208:father:3
3075771200:This is a new pthread:3
3075774208:father:4
3075771200:This is a new pthread:4
3075774208:wait the new pthread
3075771200:This is a new pthread:5
3075771200:This is a new pthread:6
3075771200:This is a new pthread:7
3075771200:This is a new pthread:8
3075771200:This is a new pthread:9
3075774208:over

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stone8761

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值