protothread jump a thread to the beginning in the external main function

115 Views Asked by At

I have a protothread set up and blocking ...

static int mythread(struct pt *pt){
  static int k;
  PT_BEGIN(pt)
  while(1){
     PT_WAIT_UNTIL(pt, eventA == 1);  // blocked at lineA

     for(k=0;k<100;k++){
        //do something
        PT_YIELD(pt);   //blocked at lineB
     }

     PT_WAIT_UNTIL(pt, eventB == 1);  //block at lineC
  }
  PT_END(pt)
}

After a while, mythread can be blocked at "lineA", "lineB", or "lineC".

How could an external function, like main() reset mythread to be blocked at the beginning "lineA" again.

By running the macro PT_RESTART(&pt_mythread)? The compiler doesn't like it. Because my main() function isn't inside PT_BEGIN, PT_END block, so the return inside that macro is bad, bad.

Or running PT_INIT(&pt_mythread) again? Any suggestions?

1

There are 1 best solutions below

0
On

Yes, calling PT_INIT from outside the protothread will restart it. If you look at the source for PT_RESTART:

#define PT_RESTART(pt)              \
  do {                      \
    PT_INIT(pt);                \
    return PT_WAITING;          \
  } while(0)

This is exactly what it does, but then also returns (like a yield) out of the thread. As you say it's designed to be called from inside the protothread.

The protothread struct is basically just a number representing where it was in the thread:

struct pt {
  lc_t lc; // where lc_t is an unsigned short;
};

So the only thing we need to do is reset that number to zero, which is exactly what PT_INIT does.