【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\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 }

結果如下:

  每次傳遞的時候,都需要轉化成void,接收之后,再由void轉換成自己需要的類型!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM