?!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
一、c语言与函数式~程模式Qfuncitonal programmingQ?/strong>
1Qc语言通过函数指针Q函数指针可以作为参敎ͼ也可以作回|对funcitonal programming提供一定的支持
2Q但又远不够强大Q本w不支持闭包Q嵌套定义等Q远未达到funcitonal programming中first class function(high order function)的境?br style="margin: 0px; padding: 0px;"/>
二、c语言标准中对函数指针的阐?/strong>
1Q函数指针可以进行类型{换,也就是从一U函数指针类型{换成另一U?/span>
2Q但不支持函数指针非兼容cdQ两个函数指针具有不同的q回值等Q的调用Q可能会破坏?br style="margin: 0px; padding: 0px;"/>
三、D例说明(wrapper functionZQ?/strong>
1QTaskCreate创徏一个线E,入口函数为entryPoint,׃entryPoint的函数类型和pthread_create中的函数cd不同
2Q若直接q行转换可能会引入上文提到的风险
3) 所以封装一entry_wrapper函数Q同时将entryPoint作ؓU程入口函数参数传递给pthread_create
源码如下Q?/span>
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_priZ喎�"http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcml0eT1tYXBfcmFuZ2VfT3NwKGRQcmlvcml0eSwgMCwgMjU1LCAxLCA5OSk7PGJyPgo8YnI+CmlmKGRTdGFja1NpemU8UFRIUkVBRF9TVEFDS19NSU4pPGJyPgpkU3RhY2tTaXplPVBUSFJFQURfU1RBQ0tfTUlOOzxicj4KaWYocHRocmVhZF9hdHRyX2luaXQoJmFtcDthdHRyKSE9MCk8YnI+CnJldHVybiAtMTs8YnI+CnByaW50Zig=" %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 functionQ?/strong>
1Qentry_wrapper本n有局限,若TaskCreate的定义如下:
int TaskCreate(UINT8 sName[], UINT32 dStackSize, void (*entryPoint)(void*),INT32 dPriority, void *pPara, UINT32 *pTaskId)
也就是pPara不ؓI,那例子中pPara׃能用来传递entryPoint,那上文中的entry_wrapper无法正常工作了
2Q解x问题的策略,可用高阶函数Q接收一个函C为参敎ͼq返回一个新的函数指针)Q高阶函数的定义需满下述条g之一
函数作ؓ另一个函数的inputQ也是参数
函数作ؓ另一个函数的outputQ也是q回?/span>
高阶函数?lua代码CZQ?/span>
function newCounter ()
local i = 0
return function () -- anonymous function
i = i + 1
return i
end
end