下面的函数不起作用。pin_thread_function有时接收垃圾而不是结构数据。怎么啦?我知道这是一些与范围有关的基本问题,但我无法解释。
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);
}当params在pthread_create之前是malloc‘c’时,一切都很好,如下所示:
...
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;
...发布于 2016-07-28 15:45:49
struct pin_thread_params params是静态分配的,其地址是,而不是,一旦其作用域结束(即在pin_monitor_create返回之后),就可以安全地使用它。有时,线程执行会在pin_monitor_create退出之前启动,并且在params中看到有效的数据。但是,动态分配的内存来自堆,在释放它之前是可用的,因此始终在params中获得pin_thread_function中的有效数据。
发布于 2016-07-28 15:33:27
我并不特别了解p线程(还不能进行相当的注释),但是您正在将一个指向堆栈分配的内存的指针传递给线程,这个线程最终会通过函数调用而失败。
https://stackoverflow.com/questions/38640658
复制相似问题