我需要将多个参数传递给我想在一个单独的线程上调用的函数.我已经读过,执行此操作的典型方法是定义结构,向函数传递指向该结构的指针,并为参数取消引用它.但是,我无法让它工作:
#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 */
}
Run Code Online (Sandbox Code Playgroud)
这个输出应该是:
5
7
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,我实际得到:
141921115
-1947974263
Run Code Online (Sandbox Code Playgroud)
谁知道我做错了什么?
sig*_*ice 72
因为你说
struct arg_struct *args = (struct arg_struct *)args;
代替
struct arg_struct *args = arguments;
Aka*_*wal 16
使用
struct arg_struct *args = (struct arg_struct *)arguments;
Run Code Online (Sandbox Code Playgroud)
代替
struct arg_struct *args = (struct arg_struct *)args;
Run Code Online (Sandbox Code Playgroud)
小智 5
main()有它自己的线程和堆栈变量。在堆中为“args”分配内存或使其成为全局:
struct arg_struct {
int arg1;
int arg2;
}args;
//declares args as global out of main()
Run Code Online (Sandbox Code Playgroud)
然后当然将引用从args->arg1到args.arg1等。