码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-09-21 13:25:28      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:std   stdio.h   print   printf   har   实例   join   null   send   

#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;//传入的结构体指针强制转为实例化结构体*v
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】——如何用线程进行参数的传递

标签:std   stdio.h   print   printf   har   实例   join   null   send   

原文地址:http://www.cnblogs.com/dpf-learn/p/7567611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!