Linux线程体传递参数的方法详解

  传递参数的两种方法

  线程函数只有一个参数的情况:直接定义一个变量通过应用传给线程函数。

  例子

  #include

  #include

  using namespace std;

  pthread_t thread;

  void * fn(void *arg)

  {

  int i = *(int *)arg;

  cout<<"i = "<<i<<endl;

  return ((void *)0);

  }

  int main()

  {

  int err1;

  int i=10;

  err1 = pthread_create(&thread, NULL, fn, &i);

  pthread_join(thread, NULL);

  }

  操作系统以进程为单位分配资源。

  线程是执行单位,线程函数有多个参数的情况:这种情况就必须申明一个结构体来包含所有的参数,然后在传入线程函数。

  具体请查看代码:

  Mularg.c

  #include

  #include

  #include

  #include

  typedef struct arg_struct ARG ;

  struct arg_struct {

  char name[10] ;

  int age ;

  float weight ;

  } ;

  void * thfn ( void * arg )

  {

  ARG * p = (ARG *) arg ;

  printf( " name is : %s , age is : % d , weight is : %f \ n " , p->name , p->age , p->weight ) ;

  return NULL ;

  }

  int main(int argc , char *argv [ ] )

  {

  pthread_t tid ;

  ARG arg ;

  int err ;

  strcpy ( arg.name , " zhanggd " ) ;

  arg.age = 26 ;

  arg.weight = 70 ;

  err = pthread_create ( &tid , NULL , thfn , (void *) & arg ) ;

  if( err != 0 ) {

  printf( " can’ˉt create thread %s\n", strerror(err) ) ;

  exit(1);

  }

  return 0 ;

  }

  程序执行结果:

 

原文链接:http://www.maiziedu.com/wiki/process/pass/

 

转载于:https://www.cnblogs.com/maizi008/p/6165568.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值