我需要将多个参数传递给一个我想在单独线程上调用的函数。我有 read做到这一点的典型方法是定义一个结构,向函数传递一个指向它的指针,然后为参数取消引用它。但是,我无法让它工作:
#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 */
}
这个的输出应该是:
5
7
但是当我运行它时,我实际上得到:
141921115
-1947974263
有人知道我做错了什么吗?
最佳答案
因为你说
struct arg_struct *args = (struct arg_struct *)args;
代替
struct arg_struct *args = arguments;
关于c - pthread_create() 调用的函数有多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1352749/