Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cpost(.. , .param)的一个问题 #9

Open
jasheri opened this issue Dec 29, 2021 · 5 comments
Open

cpost(.. , .param)的一个问题 #9

jasheri opened this issue Dec 29, 2021 · 5 comments

Comments

@jasheri
Copy link

jasheri commented Dec 29, 2021

cpost(test_cpost, .param = &s_Param, .attrs.flag = CPOST_FLAG_ADD_NEW);
例如cpost调用函数如上,这里有一个问题就是
.param = &s_Param
这里s_Param是一个静态变量,关键点在于
当还未来得及回调 cpostProcess();的时候,s_Param的值就发生了改变的话,那么等到cpostProcess回调时是传入执行函数的参数
也就发生了改变,再者如果s_Param是某个函数内的非静态变量,那么当cpostProcess回调时传入执行函数的参数应该是不可预知的,
因为.param最后记住的是一个地址。

是否考虑在cpost内部增加一个s_Param的值的副本来实现入参值的保存?

@NevermindZZT
Copy link
Owner

传入的参数是有副本保存的

            cposhHandlers[i].time = 
                param->delay ? CPOST_GET_TICK() + param->delay : 0;
            cposhHandlers[i].handler = (void (*)(void *))(param->handler);
            cposhHandlers[i].param = param->param;

@jasheri
Copy link
Author

jasheri commented Dec 30, 2021

这里的副本只是保存的指针,指针指向的对象并没有副本来保存,这里并不能够保证主函数调用cpostProcess()的时候,参数的值还是原来传入的那个值,比如原来传入进来的值是一个中断计数变量a,它在中断的时候a会加1,在中断时调用cpost(test_cpost, .param = &a); test_cpost是用来打印a的值,当程序在主函数中调用cpostProcess()时test_cpost()打印出来的a值为多少?

@NevermindZZT
Copy link
Owner

这里的参数设计只保留指针,参数的生命周期需要调用方来维护

@jasheri
Copy link
Author

jasheri commented Dec 30, 2021

这里即使参数是在生命周期内,比如a是一个全局变量,也无法保证打印出来的a值是多少,当然这里也可以让调用者管理,确保该值在打印之前不变,但是这个就很难管理了

@NevermindZZT
Copy link
Owner

基本类型可以直接强转传递,不存在这个问题
结构体类型,使用内存分配,r然后handler中释放内存,这个做法使用成本不高,其实rtos中的任务参数等也是通过这种方式做的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants