C oroutine

Keywords: Programming Python C

Donald Knuth said:

"A subroutine is a special case of a protocol."

In the process of programming, the most commonly used is the function call. At this time, for the caller, the called function is subroutine. It is possible to understand the functions that cooperate with each other. Functions can be switched between each other and can be restarted from the last switched state.
The yield keyword in a python program can stop a function from executing and keep it in execution until it is called again.

   
def rangeN(a, b): 
    i = a 
    while (i < b): 
        yield i 
        i += 1    
  
for i in rangeN(1, 5): 
        print(i) 

If we think of a coprocess as a function of cooperating with each other, how to understand "subroutines are a special case of a coprocess". What about this sentence?
In the classical c program, the function call is based on the stack. After the function call, all the information goes out of the stack, the function is called to finish execution, and the state is lost. c language does not have such keywords as yield, so how to switch a function back and forth?

  1. Static variables are used to record the execution status of the function.
  2. Use the goto keyword to jump to the necessary execution point.
int rangeV2(int a, int b) {
        static long long int i;
        static int state = 0;
        switch (state) {
                case 0:
                        state = 1;
                        i = a;
                        while (i < b) {
                                return i;

L:i++;
                        }
                        state = 0;
                        return 0;
                case 1:
                        goto L;
        }
}


int main() {
        int i;
        //for (; i = range(1, 5);) {
        //      printf("debug>>>>>%d\n", i);
        //}
        //
        i = rangeV2(1, 5);
        while (i != 0) {
                printf("debug>>>>%d\n", i);

                i = rangeV2(1, 5);
        }
}

If you don't want to use the goto keyword, you can use the duff's device. This article To achieve:

int range(int a, int b) {
        static long long int i;
        static int state = 0;
        switch (state) {
                case 0:
                        state = 1;
                        //for (i = a; i < b; i++) {
                        //      return i;
                        //      case 1:;
                        //}

                        i = a;
                        while (i < b) {
                                return i;

                                case 1:
                                i++;
                        }
        }
        state = 0;
        return 0;
}

Posted by BillyB on Sun, 27 Jan 2019 15:42:14 -0800