我想创建 n 个线程。然后分别向它们传递一个结构,以用数据填充该结构;例如一个 bool 值,用于跟踪线程是完成还是被终止信号中断。
n = 5; // For testing.
pthread_t threads[n];
for(i=0; i<n; i++)
pthread_create(&threads[i], &thread_structs[i], &functionX);
假设 thread_structs 已分配。
在 functionX()
中注意函数没有参数。我应该为结构创建一个参数吗?或者我传递结构的地方可以吗?
如何指向刚刚传递给函数的结构?
最佳答案
那不是你使用 pthread_create 的方式:
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 作为第二个参数提供)。
关于创建线程并将结构传递给它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19751190/