2011-11-22 77 views
8

我想将两个参数传递给C中的线程。我创建了一个数组(大小为2),并试图将该数组传递给线程。这是将多个参数传递给线程的正确方法吗?如何将多个参数传递给C中的线程

// 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); 
+1

检查你的代码,您声明指针数组为int和分配他们与int值。 – Teudimundo

+0

我注意到了这个警告。如果参数不是指针而只是一个数组是否合法? –

+0

如果将参数声明为int(“int parameter [2];”)的数组,则可以将参数作为指针传递。它是指向第一个int的指针。然后可以以线程的形式作为数组访问它。 – Teudimundo

回答

15

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

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. 
+3

当然,在如上例所示的代码中,您必须确保在线程尝试取消引用给定参数时不会破坏结构。 –

+0

最简单的解决方法是'malloc'结构并使新线程负责释放它。另一种方法是在结构中放置屏障,并在原始线程返回之前使原始线程和新线程都在屏障上等待。 –

+0

@FrerichRaabe也许一个愚蠢的问题,但结构如何“被销毁”......除了调用'free()'(如果它是'malloc'ed)或函数返回(如果它被分配在堆栈),还有其他方法吗? – The111

1

这是一种方法。另一个通常的方法是将指针传递给struct。这样你可以有不同的“参数”类型,并且参数被命名而不是索引,这可以使代码有时易于阅读/遵循。