c语言线程中传输多个参数

前言:c语言中创建一条线程,但是需要传送多个参数给线程的话我们自然会想到通过传送数组或者结构体来实现,下面我们来看看如何在创建线程的时候传送结构体和数组。

 1 #include <stdio.h>
 2 #include <pthread.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 
 6 typedef struct Student
 7 {
 8    int num;
 9    char name[10];
10 }info;
11 
12 void *message(void *arg)
13 {
14   info *p = (info*)arg;
15   printf("num:%d name:%s\n",p->num,p->name);
16 
17 }
18 
19 void *read_routine1(void *arg)
20 {    int *fd;
21     fd = (int*)arg;
22     // fd[0] = ((int *)arg)[0];
23     // fd[1] = ((int *)arg)[1];
24     printf("fd[0]:%d  fd[1]:%d\n",fd[0],fd[1]);
25 }
26 
27 
28 int main(int argc,char *argv[])
29 {    
30     info *st = (info*)malloc(sizeof(info));
31     st->num = 10;
32     strcpy(st->name,"xiaoming");
33     int fd[2];
34     fd[0] = 12;
35     fd[1] = 32;
36     pthread_t tid1,tid2;
37     /*创建两条线程,第一条传送的是一个结构体,第二条是数组*/
38     pthread_create(&tid2,NULL,message,(void*)st);
39     pthread_create(&tid1,NULL,read_routine1,(void*)fd);
40     while(1);
41     free(st);
42     return 0;
43 }

 经测试,这种方法是可行的。

posted @ 2018-02-08 12:18  沙漠里的孤鲸  阅读(1503)  评论(0编辑  收藏  举报