我需要将多个参数传递给我想在一个单独的线程上调用的函数.我已经读过,执行此操作的典型方法是定义结构,向函数传递指向该结构的指针,并为参数取消引用它.但是,我无法让它工作:
#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)
但是当我运行它时,我实际得到: …
这听起来有点像面试问题,但实际上是一个实际问题.
我正在使用嵌入式平台,并且仅提供这些功能的等价物:
此外,printf()实现(和签名)很可能在不久的将来发生变化,因此对它的调用必须驻留在一个单独的模块中,以便以后易于迁移.
鉴于这些,我可以在一些函数或宏中包装日志记录调用吗?目标是我的源代码THAT_MACRO("Number of bunnies: %d", numBunnies);在一千个地方调用,但是只能在一个地方看到对上述函数的调用.
编译器:arm-gcc -std = c99
我试图将2个无符号整数传递给C中新创建的线程(使用pthread_create())但是也没有2个整数或结构的数组似乎有效.
// In my socket file
struct dimension {
unsigned int width;
unsigned int height;
};
unsigned int width, height;
void setUpSocket(void* dimension) {
struct dimension* dim = (struct dimension*) dimension;
width = dim->width;
height = dim->height;
printf("\n\nWidth: %d, Height: %d\n\n", width, height);
}
// In main.cpp
// Pass a struct in pthread_create
struct dimension dim;
dim.width = w;
dim.height = h;
pthread_create(&ph, &attr, (void * (*)(void *)) setUpSocket, (void *) &dim);
Run Code Online (Sandbox Code Playgroud)
在调用pthread_create之前,dim.width和dim.height是正确的.在我的套接字文件中,只设置了宽度,高度为0,我不明白为什么.
有谁知道什么是错的,请问如何解决?
非常感谢你.