protothread示例之多線程交替執行

#include <stdio.h>

#include "pt.h"

static int protothread1_flag, protothread2_flag;

static int protothread1(struct pt *pt)
{
	PT_BEGIN(pt);
	
	while(1) {
		//釋放 CPU,等待 protothread2_flag 標識位不爲零再繼續執行
		PT_WAIT_UNTIL(pt, protothread2_flag !=0);
		printf("protothread1 running \n");
		
		protothread1_flag = 1;
		protothread2_flag = 0;
	}
	
	PT_END(pt);
}


static int protothread2(struct pt *pt)
{
	PT_BEGIN(pt);
	
	while(1) {
		
		protothread2_flag = 1;
		
		//釋放 CPU,等待 protothread1_flag 標識位不爲零再繼續執行
		PT_WAIT_UNTIL(pt, protothread1_flag != 0);
		printf("protothread2 running \n");
		
		protothread1_flag = 0;
	}
	
	PT_END(pt);
}



static struct pt pt1, pt2;
//效果: 2 個 PT 交替執行
int main()
{
	//初始化 PT
	PT_INIT(&pt1);
	PT_INIT(&pt2);

	while(1) {
		//循環調用 PT
		protothread1(&pt1);
		protothread2(&pt2);
	}

	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章