如何将多个参数传递在C线程 [英] How to pass multiple parameters to a thread in C

查看:163
本文介绍了如何将多个参数传递在C线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想两个参数传递给C中的线程我已经建立(大小2)数组,我试图传递数组的线程。这是传递多个参数到一个线程的正确方法?

 输入//参数。这是两个随机数
INT track_no =兰特()%15; //获得轨道号的线程
INT数=兰特()%20 + 1; //这个重新presents需要做的工作
为int *参数[2];
参数[0] = track_no;
参数[1] =号;//线程这里创建
的pthread_t server_thread;
INT server_thread_status;
//莫名其妙地传递两个参数代入螺纹
server_thread_status = pthread_create的(安培; server_thread,NULL disk_access,参数);


解决方案

既然你在一个空指针传递,它可以指向任何东西,包括一个结构,按照以下的例如:

  typedef结构s_xyzzy {
    INT NUM;
    焦炭名[20];
    漂浮的秘密;
} XYZZY;XYZZY plugh;
plugh.num = 42;
的strcpy(plugh.namepaxdiablo);
plugh.secret = 3.141592653589;状态=在pthread_create(安培; server_thread,NULL,disk_access,&安培; plugh);
//在pthread_join下来这里的某个地方,以确保plugh
//而server_thread正在使用它留在范围内。

I am trying to pass two parameters to a thread in C. I have created an array (of size 2) and am trying to pass that array into the thread. Is this the right approach of passing multiple parameters into a thread ?

// parameters of input. These are two random numbers 
int track_no = rand()%15; // getting the track number for the thread
int number = rand()%20 + 1; // this represents the work that needs to be done
int *parameters[2];
parameters[0]=track_no;
parameters[1]=number;

// the thread is created here 
pthread_t server_thread;
int server_thread_status;
//somehow pass two parameters into the thread
server_thread_status = pthread_create(&server_thread, NULL, disk_access, parameters);

解决方案

Since you pass in a void pointer, it can point to anything, including a structure, as per the following example:

typedef struct s_xyzzy {
    int num;
    char name[20];
    float secret;
} xyzzy;

xyzzy plugh;
plugh.num = 42;
strcpy (plugh.name, "paxdiablo");
plugh.secret = 3.141592653589;

status = pthread_create (&server_thread, NULL, disk_access, &plugh);
// pthread_join down here somewhere to ensure plugh
//   stay in scope while server_thread is using it.

这篇关于如何将多个参数传递在C线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆