zoukankan      html  css  js  c++  java
  • 【C】——如何用线程进行参数的传递

      直接上代码:

     1 #include<pthread.h>
     2 #include<stdio.h>
     3 
     4 struct val{
     5     int num1;
     6     int num2;
     7 };
     8 
     9 //send a int to arg
    10 void *text(void *arg)
    11 {
    12     int *p = (int *)arg;
    13     printf("arg is %d
    ",*p);
    14     pthread_exit(NULL);
    15 }
    16 
    17 //send char to arg
    18 void *text2(void *arg)
    19 {
    20     char *d = (char *)arg;
    21     printf("arg is %s
    ",arg);
    22     pthread_exit(NULL);
    23 }
    24 
    25 //send a struct to arg
    26 void *text3(void *arg)
    27 {
    28     struct val *v = (struct val *)arg;
    29     printf("arg is v.num1:%d,v.num2:%d
    ",v->num1,v->num2);
    30     pthread_exit(NULL);
    31 }
    32 
    33 int main()
    34 {
    35     pthread_t pth;
    36     char val[10] = "i am arg.";
    37     int arry = 10;
    38     pthread_create(&pth, NULL, text,(void *)&arry);
    39     pthread_join(pth, NULL);
    40     
    41     pthread_create(&pth, NULL, text2, (void *)val);
    42     pthread_join(pth, NULL);    
    43 
    44     struct val v;
    45     v.num1 = 0;
    46     v.num2 = 1;
    47     pthread_create(&pth, NULL, text3, (void *)&v); //一定要用&v因为结构体是值类型;
    48     pthread_join(pth, NULL);
    49 
    50     return 0;
    51 }

    结果如下:

      每次传递的时候,都需要转化成void,接收之后,再由void转换成自己需要的类型!

  • 相关阅读:
    关于PHP引用(符号&)的用法
    inline元素相关
    内联元素的margin属性
    chrome 开发者工具使用详情
    闭包 by 5wilon
    容易失忆的css
    题目:吃西瓜
    题目:装箱问题
    题目:最小乘车费用
    题目:竞赛真理
  • 原文地址:https://www.cnblogs.com/ngnetboy/p/3391368.html
Copyright © 2011-2022 走看看