Posted on 2013-05-19 15:12
S.l.e!ep.¢% 閱讀(802)
評論(0) 編輯 收藏 引用 所屬分類:
C++
Protothreads是個好東西,
官網在此 http://www.sics.se/~adam/pt/index.html
二話不說,上代碼
#include?"pt.h"?
#include?<stdio.h>
#include?<stdlib.h>
static??int??countrer;??
?
??
PT_THREAD(?example(struct??pt??*pt1)?)??
{??
????int?i?=?0;
????PT_BEGIN(pt1);??
????i?=?100;
????printf("before?i?=?%d\n",?i);
????PT_WAIT_UNTIL(pt1,?countrer?==?5?);??
????
????printf("Threshold?reached\n");??
????printf("after?i?=?%d\n",?i);
????PT_END(pt1);??
}??
int?main(void)??
{??
????static??struct??pt??example_pt;?
????countrer?=?0;??
????PT_INIT(&example_pt);??
????
????while(1)
????{
????????if(?PT_ENDED?==?example(&example_pt)?)
????????????break;
????????countrer++;??
????}
????return?0;??
}??
原理很簡單, 宏展開就是
#include?<stdio.h>
#include?<stdlib.h>
#define?PT_WAITING?0
#define?PT_ENDED?3
typedef?unsigned?short?lc_t;
struct?pt?
{
????lc_t?lc;
};
static??int??countrer;??
??
char?example(struct??pt??*pt1)
{??
????int?i?=?0;
//////////////////////////////////////////////////////////////////////////?begin
????{?
????????switch((pt1)->lc)?
????????{?????
????????case?0:
//////////////////////////////////////////////////////////////////////////?-begin
????????????while(1)?
????????????{??
//////////////////////////////////////////////////////////////////////////?call
????????????????do?{????????
????????????????????(pt1)->lc?=?__LINE__;?case?__LINE__:
????????????????????if(?!(?countrer?==?5?)?)?
????????????????????{
????????????????????????return?PT_WAITING;????
????????????????????}????????????????????????
????????????????}?while(0);
//////////////////////////////////////////////////////////////////////////?-call
????????????????printf("Threshold?reached\n");??
????????????????countrer?=?0;??
????????????????exit(1);
????????????}??
//////////////////////////////////////////////////////////////////////////?end
????????}?
????????(pt1)->lc?=?0;
????????return?PT_ENDED;
????}
//////////////////////////////////////////////////////////////////////////?-end
}
int?main(void)??
{??
????static??struct??pt??example_pt;?
????countrer?=?0;??
????(&example_pt)->lc?=?0;
????
????while(1)
????{
????????example(&example_pt);??
????????countrer++;??
????}
????return?0;??
}??
有個壞處, 寫代碼時
?i = 100;????????????????????????????????????? <-----?這里賦了值
?printf("before i = %d\n", i);
到了
?printf("Threshold reached\n");?
?printf("after i = %d\n", i);????????????? <----- 到了這里你還以為i 是 100? 錯了....
不過用于解決?
http://www.shnenglu.com/sleepwom/archive/2013/05/19/200390.html?
我在這篇文章提出的問題, 提供了一種思路.