我想创建n个线程然后向它们传递一个结构,每个结构用数据填充该结构;例如bool,用于跟踪线程是完成了还是被终止信号中断了。
n = 5; // For testing.
pthread_t threads[n];
for(i=0; i<n; i++)
pthread_create(&threads[i], &thread_structs[i], &functionX);
假设线程结构已被malloced。
在
functionX()
Notice函数中没有参数我应该为结构创建一个参数吗或者我要经过的地方可以吗?如何指向刚传递给函数的结构?
最佳答案
这不是使用pthread创建的方法:
http://man7.org/linux/man-pages/man3/pthread_create.3.html
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
第三个参数是您的例程,第四个参数将被转发到您的例程。你的程序应该是这样的:
void* functionX(void* voidArg)
{
thread_struct* arg = (thread_struct*)voidArg;
...
pthread调用应该是:
pthread_create(&threads[i], NULL, functionX, &thread_structs[i]);
(除非有pthread_attr_t作为第二个参数提供)。
关于c - 创建一个线程并将结构传递给它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19751190/