Linux创建线程函数

Linux创建线程函数

线程创建函数 pthread _create()

函数原型

int pthread_create(pthread_t* restrict tidp,const pthread_attr_t* restrict_attr,
void* (*start_rtn)(void*),void *restrict arg);

参数解释:

pthread_t* restrict tidp

首先需要定义一个线程id;声明为

pthread_t id;
//或者声明为指针类型
pthread_t *pid;// 指向线程id的指针

它并不需要初始化,在系统pthread _create()函数后会自动为id赋值,方便后面使用

const pthread_attr_t* restrict_attr

它是线程属性,我们一般默认为NULL

void* (start_rtn)(void)

它是一个函数指针,表示在当前新创建的线程中执行这个函数,在函数定义的时候要在函数名前加*。

void *restrict arg

线程要运行函数的参数。无参数时设为NULL,有参数时输入参数的地址,当多于一个参数时应当使用结构体传入(取地址)。

函数返回值

成功返回0,否则返回错误码。

阻塞等待线程函数pthread_jion()

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

参数解释

pthread_t thread表示传入的线程id,通过它可以知道需要等待哪个线程结束。
void **value_ptr);表示退出信息。

代码示例

创建三个线程,这三个线程都会执行fun函数,只有线程一会在main函数等待线程一函数结束。main函数结束该程序就会结束,其余未执行的线程都会终止。

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

void *fun(void* arg){
   for(int i=0;i<5;i++){
    printf("%d",i);
   }
}
int main(){
    pthread_t id1;
    pthread_t id3;
    pthread_t id2;

    pthread_create(&id1,NULL,&fun,NULL);
    pthread_create(&id2,NULL,&fun,NULL);
    pthread_create(&id3,NULL,&fun,NULL);

    pthread_join(id1,NULL);
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值