我需要将多个参数传递给我想在单独线程上调用的函数。我有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 = 参数;
关于c - pthread_create() 调用的函数有多个参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30962190/