在 C/C++ 中,协程是通过堆栈交换 hack 实现的,因此堆栈大小通常是有限的,不会自动增长。
D Fiber 有这些限制吗?还是会自动增长?
我尝试使用 4K 初始光纤大小,如果第一个堆栈溢出 4K,D Fiber 会崩溃。无论如何,一旦屈服,它在子程序中保留了超过 8K 的堆栈数组变量。因此,每次产量似乎都会增加堆栈。所以这不仅仅是安全的,程序员需要关心堆栈大小。
此外,printf
无论堆栈大小如何,D 都会崩溃……我不知道为什么……这是我的测试代码。
import std.stdio;
import std.concurrency;
import core.thread;
import std.container;
import std.conv;
void main()
{
Fiber[] fs = new Fiber[10];
foreach (int i; 0..cast(int)fs.length)
{
fs[i] = new F1(i);
};
foreach (ref Fiber f ; fs)
{
f.call();
};
foreach (ref Fiber f ; fs)
{
f.call();
};
foreach (ref Fiber f ; fs)
{
auto s = f.state;
writeln(s);
};
}
class F1 : Fiber
{
this(int idx)
{
super(&run, 4096);
_idx = idx;
}
private:
int _idx;
void run()
{
byte[3700] test1;
//byte[1024] test2;
writeln(_idx);
//t1();
this.yield();
t1();
//byte[1024] test3;
//byte[1024] test4;
writeln(_idx);
}
void t1()
{
byte[4096] test;
//printf("T1!");
t2();
}
void t2()
{
byte[2048] test;
//printf("T2!");
//t3();
}
void t3()
{
byte[2048] test;
printf("T3!");
}
}
当前结果。
0
1
2
3
4
5
6
7
8
9
0
./build.bash: line 11: 26460 Segmentation fault: 11 ./tester