使用pthread_create()时将结构作为参数传递

时间:2009-05-14 15:15:26

标签: c multithreading struct pthreads

我尝试将结构作为第4个参数传递,同时使用pthread_create()使用类似的东西:

pthread_create(&tid1, NULL, calca, &t); //t is the struct

现在每当我尝试访问结构中的变量 - t.a,t.b或t.c时,我都会收到错误 - 请求成员不是结构或联合。

我可以使用什么替代方法将结构传递给线程?

8 个答案:

答案 0 :(得分:24)

您可能在与pthread_create相同的范围内创建结构。退出该范围后,此结构将不再有效。

尝试在堆上创建指向结构的指针,并将该结构指针传递给您的线程。不要忘记在某个地方删除那个内存(如果你再也不会使用它,那么就在线程中删除它 - 或者当你不再需要它时)。

此外,正如网络控制所提到的,如果您要从不同的线程访问该数据,您需要使用互斥锁或关键部分锁定对它的访问权。

编辑美国东部时间2009年5月14日美国东部时间下午12:19 :另外,正如其他人提到的那样,您必须将参数转换为正确的类型。

如果您传递的是一个全局结构的变量(您似乎坚持这样),您的线程函数将必须转换为类型:

void my_thread_func(void* arg){
    my_struct foo = *((my_struct*)(arg)); /* Cast the void* to our struct type */
    /* Access foo.a, foo.b, foo.c, etc. here */
}

或者,如果要传递指向结构的指针:

void my_thread_func(void* arg){
    my_struct* foo = (my_struct*)arg; /* Cast the void* to our struct type */
    /* Access foo->a, foo->b, foo->c, etc. here */
}

答案 1 :(得分:2)

如果你在线程函数中,你传递的参数是void *。您需要先将其强制转换为结构,然后才能使用它。

void my_thread_func(void* arg){
    my_struct foo = (my_struct)(*arg); /* Cast the void* to our struct type */
    /* Access foo.a, foo.b, foo.c, etc. here */
}

答案 2 :(得分:1)

  1. 创建信号量

  2. 创建另一个结构,该结构由指向结构和信号量句柄的指针组成

  3. 将指向此新结构的指针传递给pthread_create

  4. 在父线程中,即调用pthread_create,等待信号量

  5. 在子线程中,将结构的成员复制到本地变量或将其保存到别处

  6. 在子线程中,发出信号量信号

  7. 在父线程中,关闭信号量

答案 3 :(得分:0)

您可以使用共享内存或全局变量(如果没有其他内容需要该参数)或链接列表(如果这些是以数据为基础的线程)。

请记住锁定正在进行线程共享的变量。

虽然没有实际的违规代码,但我无法告诉你当前实施中你做错了什么。

答案 4 :(得分:0)

此错误消息表示您没有取消引用指针。

你说“t.a”而不是“t-> a”

[me@myhost ~]$ cat testitx.c
struct x {
        int a, b;
};

int main(int argc, char *argv[])
{
        struct x y, *z;

        z = &y;
        z.a = 10;
}
[me@myhost ~]$ cc -c testitx.c
testitx.c: In function `main':
testitx.c:10: error: request for member `a' in something not a structure or union
[me@myhost ~]$

答案 5 :(得分:0)

我经常习惯于在其他答案中列出相同的错误,但现在我采用了一种稍微不同的方法,将错误的可能性从线程函数转移到pthread_create调用。

我以'正常'的方式声明和定义线程函数:

void *ThreadFunction(sPARAMETERS *Params) {

  // do my threading stuff...

}

当我调用pthread_create时,我需要使用强制转换:

pthread_create(&ThreadId,0,(void*(*)(void*)) &ThreadFunction,&Params);

我几乎永远不会忘记使用&在Params上,编译器将处理我在另一端犯的任何错误。也适用于回调。

答案 6 :(得分:0)

my_struct foo =(my_struct)(* arg);是内心的 尝试 my_struct * foo =(my_struct *)(arg);
AND,int函数调用线程, 确保它的静态(所以指向的内存,不会在迷雾中丢失)

答案 7 :(得分:0)

这是一个例子: 这是将创建线程并传递结构参数的函数

pthread_create (& threads[i], NULL , PrintMessage ,(void *) &tab[i]);

这是线程函数:

 void *PrintMessage(void * arg)
{
struct param *mes_param ; mes_param = (struct param*) arg;
printf (" message from thread %d: %s\n", mes_param -> num_message ,
mes_param -> message );
pthread_exit(NULL);
}

结构:

struct param {
int num_message ;
char* message ; };
struct param tab[MAX_THREADS];