Prothreads(超级轻量多任务)

时间:2021-08-09
本文章向大家介绍Prothreads(超级轻量多任务),主要包括Prothreads(超级轻量多任务)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

要点 :

  ①Prothreads 不是真正意义上的多任务,任务切换并不做cpu寄存器的压栈和出栈,也因此它不设计任何硬件平台的关系。

  ②Prothreads 任务中不能使用局部变量

  ③Prothreads 源码地址: Protothreads - download (dunkels.com),或者地址:https://files.cnblogs.com/files/blogs/698223/pt-1.4.tar.gz

分析源码,看这段源码就知道原理了:

example-small.c

struct pt {
lc_t lc;
};

static int
protothread1(struct pt *pt)
{
  PT_BEGIN(pt);

  while(1) {
    PT_WAIT_UNTIL(pt, protothread2_flag != 0);
    printf("Protothread 1 running\n");

    protothread2_flag = 0;
    protothread1_flag = 1;

  }

  PT_END(pt);
}

int main(void)

{
  PT_INIT(&pt1);
  PT_INIT(&pt2);

  while(1) {
  protothread1(&pt1);
  protothread2(&pt2);
  }
}

展开就是:


int main(int argc, char* argv[])
{
  Tpt* pt = &tpt;
  pt->lc = 0;

  while(1){
  //threads 1
    {
    //PT_BEGIN
    char PT_YIELD_FLAG = 1;
    switch((pt)->lc){
      case 0:
    //PT_BEGIN

        //PT_WAIT_UNTIL     这里就是精髓
        while(1){
          do{
            (pt)->lc = __LINE__;
            case __LINE__:
            if(!condition){
              return PT_WAITING;
            }
          }while(0);

        //PT_WAIT_UNTIL

        //your task here
        printf("Protothread 1 running\n"); 

        }
    //END
    }
    PT_YIELD_FLAG = 0;
    (pt)->lc = 0;
    return PT_ENDED;
    //END

  }
  //threads 1
}

return 0;
}

原文地址:https://www.cnblogs.com/ellson/p/15117831.html