【发布时间】:2015-11-06 02:38:18
【问题描述】:
这是一个来自 The Linux Programming Interface 的程序(原代码here)。我想要做的是使用pthread_create() 向 threadFunc 发送 2 个“参数”,以实现下面列出的目标:
- 第一个用作 threadFunc() 中 for 循环中的迭代器;
- 第二个标识当前在threadFunc() 中工作的线程。所以它将是线程的某种可打印 ID。
为了实现这些目标,我创建了这个包含 2 个成员变量的结构:
struct arguments {
int loops;
pthread_t self;
};
并且这个函数循环“threadFuncLoops”次递增全局变量“glob”
static void * threadFunc(void *arg)
{
struct arguments * threadFuncArgs = arg;
int threadFuncLoops = *(arg.loops);
for (int j = 0; j < threadFuncLoops; j++) {
// Something happens to glob
}
return NULL;
}
在 main() 中,我创建了 2 个线程 (t1, t2) 并将它们发送到 threadFunc():
struct arguments newArguments;
s = pthread_create(&t1, NULL, threadFunc, &newArguments);
s = pthread_create(&t2, NULL, threadFunc, &newArguments);
但是编译器在 threadFunc() 中说
request for member 'loops' in something not a structure or union
我的问题是:
- 为什么“循环”不在结构中?它在结构实例中不是吗?
- 具体如何实现目标 #2?
非常感谢。
【问题讨论】:
-
*(arg.loops);不正确。loops不是指针,因此不能被引用。此外,args是void *,因此既不是结构指针也不是结构。在很多层面上都是错误的。应该是threadFuncArgs->loops。
标签: c linux multithreading