【发布时间】:2012-08-28 21:47:15
【问题描述】:
我的问题是关于传递给线程的参数。
我有一个函数 Foo 对数组进行操作,比如 arrayA。为了加快速度,Foo 被编码为在数组的两个方向上操作。因此, Foo 将 arrayA 和一个整数 X 作为参数。根据 X 的值,它可以正向或反向运行。
我希望避免全局使用“arrayA”和“X”。因此,我将“arrayA”和“X”作为参数传递给 Foo,并创建两个线程来运行 Foo——每个方向一个。这是我所做的:
typedef struct {int* arrayA[MSIZE]; int X; } TP; //arrayPack=TP
void Foo (void *tP) {
TP *tp = (TP*)tP; // cast the parameter tP back to what it is and assign to pointer *tp
int x;
printf("\nX: %d", tp->X);
printf("\n arrayA: "); for (x=0; x<tp->arrayA.size(); printf("%d ", aP->arrayA[x]), x++);
} // end Foo
void callingRouting () {
int* arrayA[MSIZE] = {3,5,7,9};
TP tp; tp.arrayA=arrayA;
tp.X=0; _beginthread(Foo, 0, (void*)&tp); // process -- forward
tp.X=1; _beginthread(Foo, 0, (void*)&tp); // process -- reverse
}
这些值没有传递——我的数组打印为空,我没有正确打印 X 的值。我错过了什么?
我也很感激关于这方面的一些阅读建议——将参数传递给线程——尤其是关于传递线程共享的资源。谢谢。
【问题讨论】:
-
int *arrayA[MSIZE];可能是错误的大小。 -
附带说明,我看不出您在哪里进行反向迭代。我实际上建议在数组中使用偏移量而不是偏移量,这样您就可以更灵活地扩展到更多线程。
标签: c multithreading parameter-passing