uIP 中的 Protothread 原理分析

uIP 是单片机系统中 TCP/IP 协议的一个最小实现。其中用到了一个叫 Protothread 的来模拟多线程。此文简单分析下它的原理:

Switch case 的特殊用法

先看下面的代码,分析 foobar(2) 的输出, foobar(3) 的输出。

void foobar(int status)
{
	switch (status)
	{
	case 0:
		printf("Got case0\n");
		do
		{
			case 2:
				printf("Got case2\n");
				break;
		}
		while (1);


		printf("Got p2.5\n");
		if (0)
		{
			case 3:
			printf("Got case3\n");
		}
		return;
	}
}

  • 在这里把 switch case 理解为 goto 就行了。所以 case 可以放在while 循环内也不会有语法和逻辑错误。
  • case 2 之后的 break,是break switch 呢?还是break while?在这里break的是while。参考如下:The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.
这种 switch 的用法在 Protothread 中,如果当前的条件不满足,也可以退出此函数,之后可以根据输入的状态,立刻跳转到刚才的地方(case处)。

Protothread

Protothread 通过一些宏定义来封装了上面的switch case 语句。Protothread 使用了一个变量来记录当前的状态(语句行__LINE__),case的地方就是__LINE__,而如果当前条件不符合继续执行,就退出这个函数,把当前的状态标记为__LINE__,下次再接着执行。 使用的时候,只需要关心当前的逻辑就行了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值