一、c语言与函数式编程模式(funcitonal programming)
1)c语言通过函数指针(函数指针可以作为参数,也可以作为返回值)对funcitonal programming提供一定的支持2)但又远不够强大,本身不支持闭包,嵌套定义等,远未达到funcitonal programming中first class function(high order function)的境界
1)函数指针可以进行类型转换,也就是从一种函数指针类型转换成另一种
2)但不支持函数指针非兼容类型(两个函数指针具有不同的返回值等)的调用,可能会破坏栈
1)TaskCreate创建一个线程,入口函数为entryPoint,由于entryPoint的函数类型和pthread_create中的函数类型不同
2)若直接进行转换可能会引入上文提到的风险
3) 所以封装一 entry_wrapper函数,同时将entryPoint作为线程入口函数参数传递给pthread_create
源码如下:
void *entry_wrapper (void (*entryPoint)(void))//ljc define a wrapper funciton,(tycast different signature function pointer is ok,but call it use another type may corrupt stack)
{
//entryPoint();
entryPoint();
return NULL;
}
int TaskCreate(UINT8 sName[], UINT32 dStackSize, void (*entryPoint)(void),INT32 dPriority, void *pPara, UINT32 *pTaskId)
{
pthread_t thread;
pthread_attr_t attr;
struct sched_param param_sched;
param_sched.sched_priority=map_range_Osp(dPriority, 0, 255, 1, 99);
if(dStackSize<PTHREAD_STACK_MIN)
dStackSize=PTHREAD_STACK_MIN;
if(pthread_attr_init(&attr)!=0)
return -1;
printf(" %s %d %d\n",__FUNCTION__,__LINE__,PTHREAD_STACK_MIN);
printf(" %d\n",pthread_attr_setstacksize(&attr,(size_t)dStackSize));
printf(" %d\n",pthread_attr_setschedpolicy(&attr,SCHED_RR));
printf(" %d\n",pthread_attr_setschedparam(&attr,¶m_sched));
if((pthread_attr_setstacksize(&attr,(size_t)dStackSize)!=0)||(pthread_attr_setschedpolicy(&attr,SCHED_RR)!=0)||(pthread_attr_setschedparam(&attr,¶m_sched)!=0))
return -1;
printf(" %s %d\n",__FUNCTION__,__LINE__);
// if(pthread_create(&thread, &attr,(void *(*) (void *))entryPoint,pPara)!=0)//ljc when startroutine over,it will auto call pthread_exit;take startroutine's return value as it's exit status
if(pthread_create(&thread, &attr,(void *(*) (void *))entry_wrapper,entryPoint)!=0)
return -1;
if( pthread_attr_destroy(&attr)!=0)
return -1;
if(pTaskId)
*pTaskId=(UINT32)thread;
return 0;
}
四、高阶函数(high order function)
1)entry_wrapper本身有局限,若TaskCreate的定义如下:
int TaskCreate(UINT8 sName[], UINT32 dStackSize, void (*entryPoint)(void*),INT32 dPriority, void *pPara, UINT32 *pTaskId)
也就是pPara不为空,那例子中pPara就不能用来传递entryPoint,那上文中的entry_wrapper就无法正常工作了
函数作为另一个函数的input,也就是参数
函数作为另一个函数的output,也就是返回值
高阶函数的 lua代码示例:
function newCounter ()
local i = 0
return function () -- anonymous function
i = i + 1
return i
end
end
3)高阶函数的实现,由于c语言本身的局限,实现起来相对复杂,后续再进一步说明