yield汇编实现.
#include <stdio.h #include <conio.h #include <iostream.h // // marks a location in the program for resume // does not return control, exits function from inside macro // // yield( x, ret ) // x : the 'name' of the yield, cannot be ambiguous in the // function namespace // ret : the return value for when yield() exits the function; // must match function return type (leave blank for no return type) #define yield(x,ret) { /* store the resume location */ __asm { mov _myStaticMkr,offset label_##x } /* return the supplied value */ return ret; } /* our offset in the function */ label_##x: // // resumes function from the stored offset, or // continues without notice if there's not one // stored // // resume() // <void #define resume() /* our stored offset */ static _myStaticMkr=0; /* test for no offset */ if( _myStaticMkr ) { /* resume from offset */ __asm { jmp _myStaticMkr } } // example demonstrating a function with an int return type // using the yield() and resume() macros // // myFunc() // <void int myFunc() { resume(); cout << "1 "; yield(1,1); cout << "2 "; yield(2,1); cout << "3 "; yield(3,1); cout << "4 "; return 0; } // main function // // main() // <void void main( void ) { cout << "Yield in C++ "; cout << "Chris Pergrossi "; myFunc(); do { cout << "main() "; cout.flush(); } while( myFunc() ); cout.flush(); getch(); } /* // example demonstrating a function with no return type // using the yield() and resume() macros // // myFunc() // <void void myFunc() { resume(); cout << "1 "; yield(1); cout << "2 "; yield(2); cout << "3 "; yield(3); cout << "4 "; return; } // main function // // main() // <void void main( void ) { cout << "Yield in C++ "; cout << "Chris Pergrossi "; myFunc(); for( int k = 0; k < 4; k ++ ) { cout << "main() "; cout.flush(); myFunc(); } cout.flush(); getch(); } */