Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Coroutines ใน C/C++


ในบทช่วยสอนนี้ เราจะอภิปรายโปรแกรมเพื่อเข้าใจ coroutines ใน C/C++

Coroutines คือ control instructions ที่สลับ execution control ระหว่าง 2 routines โดยไม่ return ใดๆ

ตัวอย่าง

#include<stdio.h>
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;
                //returning control
                case 1:; //resuming control
            }
    }
    state = 0;
    return 0;
}
int main(){
    int i;
    for (; i=range(1, 5);)
        printf("control at main :%d\n", i);
    return 0;
}

ผลลัพธ์

control at main :1
control at main :2
control at main :3
control at main :4