gpt4 book ai didi

c++ - 协程演示源码/2

转载 作者:行者123 更新时间:2023-11-30 03:09:09 28 4
gpt4 key购买 nike

有人可以解释为什么这段代码在codepad 上不起作用吗?修改后的版本(带有虚函数)实际上可以工作 -
工作版本 - http://codepad.org/5rRIg5zT
无效版本(下)- http://codepad.org/4PO2rBqS
我的意思是,实际上有效的 C++ 还是 codepad 编译器是错误的?

更新:还有另一种可行的方法 - http://codepad.org/j6GAKXov但它不是很自动。

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

typedef unsigned int uint;
typedef unsigned short word;
typedef unsigned char byte;

#ifdef __GNUC__
#define NOINLINE __attribute__((noinline))
#else
#define NOINLINE __declspec(noinline)
#endif

#include <setjmp.h>

enum{
STKPAD=1<<16,
STKSAV=1<<10
};

template <typename T>
struct coroutine {

volatile uint state;
volatile char* stkptrH;
volatile char* stkptrL;
jmp_buf PointA, PointB;
char stack[STKSAV];

coroutine() { state=0; }

NOINLINE // necessary for IntelC + my_setjmp.h
void yield( int value ) {
char curtmp; stkptrL=(&curtmp)-16; // -16 is necessary for MSC
if( setjmp(PointB)==0 ) {
state = value;
memcpy( stack, (char*)stkptrL, stkptrH-stkptrL );
longjmp(PointA,1);
}
}

NOINLINE // necessary for MSC, to avoid allocation of stktmp before setjmp()
void call_do_process() {
char stktmp[STKPAD]; stkptrH = stktmp;
((T*)this)->do_process();
}

uint call( void ) {
if( setjmp(PointA)==0 ) {
if( state ) {
memcpy( (char*)stkptrL, stack, stkptrH-stkptrL );
longjmp(PointB,1);
}
call_do_process();
}
return state;
}

};

struct index : coroutine<index> {

void do_process( void ) {
uint a=1;
while(1) {
yield( a );
a++;
}
}

} F1;

struct fibonacci : coroutine<fibonacci> {

void do_process( void ) {
uint a=0,b=1;
while(1) {
yield( b );
b = b + a;
a = b - a;
}
}

} F2;

int main( int argc, char** argv ) {

for( int i=0; i<20; i++ ) {
printf( "%i:%i ", F1.call(), F2.call() );
} printf( "\n" );

return 0;
}

最佳答案

在非工作版本中,如果我改变

struct index : coroutine<index> {

struct indexX : coroutine<indexX> {

然后它突然编译(使用 GCC)。显然,头文件中某处已经定义了一个“索引”,它会干扰您的代码索引。

关于c++ - 协程演示源码/2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4352451/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com