本文介绍了多参数函数通过在pthread_create()调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要多个参数传递给我想一个单独的线程调用一个函数。我阅读,要做到这一点的典型方式是定义一个结构,一个指针传递的功能这一点,解引用它的参数。但是,我无法得到这个工作:
I need to pass multiple arguments to a function that I would like to call on a separate thread. I've read that the typical way to do this is to define a struct, pass the function a pointer to that, and dereference it for the arguments. However, I am unable to get this to work:
#include <stdio.h> #include <pthread.h> struct arg_struct { int arg1; int arg2; }; void *print_the_arguments(void *arguments) { struct arg_struct *args = (struct arg_struct *)args; printf("%d\n", args -> arg1); printf("%d\n", args -> arg2); pthread_exit(NULL); return NULL; } int main() { pthread_t some_thread; struct arg_struct args; args.arg1 = 5; args.arg2 = 7; if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) { printf("Uh-oh!\n"); return -1; } return pthread_join(some_thread, NULL); /* Wait until thread is finished */ }这个输出应该是:
The output for this should be:
5 7但是当我运行它,我实际上得到:
But when I run it I actually get:
141921115 -1947974263任何人都知道我在做什么错了?
Anyone know what I'm doing wrong?
推荐答案由于你说
结构arg_struct * ARGS =(结构arg_struct *)ARGS;
而不是
结构arg_struct * ARGS =参数;
更多推荐
多参数函数通过在pthread
发布评论