linux线程创建

  1. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  2.                                      void *(*start_routine) (void *), void *arg);
  3. //线程创建函数
  4. void pthread_exit(void *retval);
  5. //线程退出函数
  6. int pthread_join(pthread_t thread, void **retval);
  7. //线程等待函数
  8. pthread_t pthread_self(void);
  9. //线程ID 获取
  • 线程创建: 
  •  int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
  •                                                 线程 ,               属性(NULL),                              调用函数,   函数传递参数         
  • 线程等待函数:
  • int pthread_join(pthread_t thread, void **retval);
  •                                   线程                退出状态

 pthread_t pthread_self(void);  // pthread_t:头文件中声明为无符号长整型参数(unsigned long

 代码如下:

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

//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//                        void *(*start_routine) (void *), void *arg);

//void pthread_exit(void *retval);

//pthread_t pthread_self(void);

void *func(void *arm)
{
        static int ret = 10;  //static定义函数,使ret值在main函数中不改变,否则ret为局部变量只在此函数中等于10

        printf("t1:%ld this is creat\n",(unsigned long)pthread_self()); // pthread_t为无符号长整型,返回的ID值要强制转换类型
        printf("t1:pram is %d\n",*((int *)arm));

        pthread_exit((void *)&ret);
}

int main()
{

        int ret;
        pthread_t t1;
        int pram = 100;

        int *pair;

        ret = pthread_create(&t1,NULL,func,(void *)&pram);

        if(ret == 0){
                printf("main:creat t1 success\n");
        }

        printf("main:%ld\n",(unsigned long)pthread_self());

        pthread_join(t1,(void **)&pair);//指向线程退出状态

        printf("main:quit is %d\n",*pair);

        return 0;
}

运行结果: 

main:creat t1 success
main:139652561684224
t1:139652553398016 this is creat
t1:pram is 100
main:quit is 10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值