创建线程并将结构传递给它

标签 c pthreads

我想创建 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/

相关文章:

c - 了解 socket() 输出

c - 如何获取调用函数的名称?

c - 接受系统调用时出现段错误

有人可以解释这两个问题的解决方案(c 程序,互斥体,线程)吗?

c - 如何使一个线程在linux中等待另一个?

c - 为什么 Eclipse 的 C 应用程序在调用 `system("clear")`(在 stdlib.h 中定义)时启动终端打印垃圾?

c - 2 个未排序数组中的第 K 个排名元素

c - Leetcode 中等问题(单链表)

C 在《哲学家就餐》中将数组传递给 pthread

C++ 获取不同线程的回溯