|
本帖最后由 LGT 于 2013-11-6 10:29 编辑
看到smset推荐的protothread, 感觉挺有意思, 看了下源代码, 把原理用一段简单的C代码解释一下,
希望对还不是很了解的同学有帮助:- #include <stdio.h>
- void thread_fsm(char *tname, unsigned char *status)
- {
- switch(*status) { case 0: // PT_BEGIN
- while(1) {
- printf("%s: Here is step 0!\n", tname);
- if('q' != getchar())
- return;
- *status = __LINE__; case __LINE__: // must be kept in same line, or the two __LINE__ will not equal
- printf("%s: Here is step 1!\n", tname);
- if('q' != getchar())
- return;
- *status = __LINE__; case __LINE__:
- printf("%s: Here is step 2!\n", tname);
- if('q' != getchar())
- return;
- printf("%s: Now return to step 0!\n", tname);
- *status = 0;
- break;
- default:
- printf("%s: Got wrong status!\n", tname);
- }
- }
- }
- int main(int argc, char *argv[]) {
-
- unsigned char status1 = 0; // PT_INIT
- unsigned char status2 = 0; // PT_INIT
-
- while(1) {
- thread_fsm("thread 1", &status1);
- thread_fsm("thread 2", &status2);
- }
-
- }
复制代码 运行上面的代码,输入q+回车,就可以看到thread的执行了。
thread的写法如果变的规范些, 然后把__LINE__替换成具体的数值,就更容易懂了:- void thread_fsm(char *tname, unsigned char *status)
- {
- switch(*status) {
- case 0: // PT_BEGIN
- while(1) {
- printf("%s: Here is step 0!\n", tname);
- if('q' != getchar())
- return;
- *status = 1;
- case 1:
- printf("%s: Here is step 1!\n", tname);
- if('q' != getchar())
- return;
- *status = 2;
- case 2:
- printf("%s: Here is step 2!\n", tname);
- if('q' != getchar())
- return;
- printf("%s: Now return to step 0!\n", tname);
- *status = 0;
- break;
- default:
- printf("%s: Got wrong status!\n", tname);
- }
- }
- }
复制代码 |
阿莫论坛20周年了!感谢大家的支持与爱护!!
知道什么是神吗?其实神本来也是人,只不过神做了人做不到的事情 所以才成了神。 (头文字D, 杜汶泽)
|