Linux线程创建

线程创建

创建线程需要用到pthread_create这个函数,需要注意的是这个函数不是系统提供的,而是一个库函数,所以用这个函数的时候要引入头文件<pthread.h>
函数原型

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

  • thread:返回线程ID
  • attr:设置线程属性,通常设置成NULL
  • start_routine:线程入口函数地址,这个函数的功能主要是线程用来处理任务的
  • arg:线程入口函数的参数
  • Compile and link with -pthread.
    链接这些函数库时,需要使用编译命令的“-lpthread”选项
    代码演示:
  1 #include<stdio.h>
  2 #include<pthread.h>
  3 #include<unistd.h>
  4 #include<stdlib.h>
  5 void* thr(void* arg){
  6   while(1){
  7     printf("i am common thread:%p\n",pthread_self());
  8     sleep(1);
  9   }
 10   return NULL;
 11 }                                                                
 12 int main(){
 13   pthread_t tid;
 14   void* arg;
 15   int ret = pthread_create(&tid,NULL,thr,arg);
 16   if(ret!=0){
 17     printf("pthread_create error\n");
 18     return -1;
 19   }
 20   while(1){
 21     printf("i am main thread\n");
 22     sleep(1);
 23   }
 24   return 0;  
 25 }          
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值