[英]How to pass a local struct as parameter to pthread_create?
The following function doesn't work. 以下功能无效。
pin_thread_function
sometimes receive garbage instead of the struct data. pin_thread_function
有时会收到垃圾而不是结构数据。 What is wrong? 怎么了? I know that is some basic scope related problem, but I can't explain.
我知道这是一些与范围有关的基本问题,但我无法解释。
typedef void (*state_callback_t)(int state);
struct pin_thread_params
{
char pin[3 + 1];
state_callback_t callback_onchange;
};
extern int pin_monitor_create(const char * pin,
state_callback_t callback_onchange)
{
int ret;
unsigned long int thread;
struct pin_thread_params params;
//Setup struct
strcpy(params.pin, "123");
params.callback_onchange = callback_onchange;
//Create thread with struc as parameter
ret = pthread_create(&thread, NULL, pin_thread_function, ¶ms);
if (!ret)
{
ret = pthread_detach(thread);
}
return ret;
}
static void * pin_thread_function(void * context)
{
struct pin_thread_params params;
memcpy(¶ms, context, sizeof(params));
//Sometimes the correct string, most time garbage
printf("Started monitoring %s", params.pin);
}
When params is malloc'ed before pthread_create, everything works fine, like this: 如果在pthread_create之前对参数进行了malloc分配,则一切正常,如下所示:
...
struct pin_thread_params * params;
//Setup struct with malloc
params = malloc(sizeof(struct pin_thread_params));
strcpy(params->pin, "123");
params->callback_onchange = callback_onchange;
...
struct pin_thread_params params
is statically allocated and the address of it is not safe to use once the scope of it is over (ie after pin_monitor_create
has returned). struct pin_thread_params params
是静态分配的,并且一旦其范围结束(即在pin_monitor_create
返回之后),它的地址就不能安全使用。 It may happen that sometimes the thread execution starts before the pin_monitor_create
has exited and you see the valid data in params
. 有时可能会发生线程执行在
pin_monitor_create
退出之前开始并且您在params
看到有效数据的情况。 However, the dynamically allocated memory is from heap and will be usable until you free it, so you always get valid data in params
within pin_thread_function
. 但是,动态分配的内存是从堆中获取的,直到释放后才可用,因此始终在
pin_thread_function
中的params
获取有效数据。
我对pthreads并不是特别了解(还不能发表评论),但是您正在向该线程传递一个指向堆栈的已分配内存的指针,该指针最终将被进行函数调用所破坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.