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__,下次再接着执行。 使用的时候,只需要关心当前的逻辑就行了。


你可能感兴趣的:(单片机-硬件)