Linux 多线程开发-线程创建pthread_creat

1、函数原型

int pthread_creat(pthread_t *pid, const pthread_attr_t *attr,void *(*start_routine)(void *),void *arg);
  1. pid:返回创建成功后的线程ID,unsigned int型变量;
  2. attr:设置线程属性,为NULL则为默认属性;
  3. start_routine:指向线程函数;
  4. arg:直线传递给线程的参数。

2、用法

(1)包含头文件 #include <pthread.h>

(2)编译连接添加 -lpthread

3、示例

示例1:不传参数

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

void thread_func(void)
{
    int i;
    for(i = 0; i < 3; i++){
        printf("thread cur cnt:%d\n",i);
    }
    printf("thread_func exit\n");
    return;
}
int main(int argc,char *argv[])
{
    pthread_t thrid;
    int ret;
    
    ret = thread_creat(&thrid,NULL,(void *(*)(void *))thread_func,NULL);
    if(ret){
        printf("pthread creat error:%d\n",ret);
        return -1;
    }

    sleep(1);
    return 0;
}

sleep(1)让main等待1秒,让线程执行。

示例2:传递整形

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

void thread_func(void *arg)
{
    int i;
    int *ptr = (int*)arg;
    int cnt = *ptr;
    printf("thread cur cnt:%d\n",cnt);
    printf("thread_func exit\n");
    return;
}
int main(int argc,char *argv[])
{
    pthread_t thrid;
    int ret;
    int n = 5;
    
    ret = thread_creat(&thrid,NULL,(void *(*)(void *))thread_func,&n);
    if(ret){
        printf("pthread creat error:%d\n",ret);
        return -1;
    }

    sleep(1);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值