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

本文探讨了在C语言中如何在线程创建时传递多个参数,建议使用结构体或数组作为参数载体,并提供了经过验证的可行性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言: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 }

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

转载于:https://www.cnblogs.com/wurenzhong/p/8430024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值