【C】——如何用线程进行参数的传递

时间:2021-08-19 20:38:21

  直接上代码:

 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\n",*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\n",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\n",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 }

结果如下:

【C】——如何用线程进行参数的传递

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