1 /// 2 module sfw.app; 3 4 import std.algorithm : filter; 5 import std.array : array; 6 import std.datetime; 7 import core.thread; 8 9 import sfw.fiber; 10 import sfw.func; 11 12 /// 13 class SFWApp 14 { 15 protected: 16 SFWFiber[] fibers; 17 /// 18 bool work = true; 19 int exit_result; 20 21 alias voidDelegate = void delegate(); 22 alias voidFunction = void function(); 23 public: 24 25 /// use for new fibers 26 size_t stackSize; 27 28 /// stackSize = 1024 * ss 29 this(size_t ss=32) { stackSize = 1024 * ss; } 30 31 /// create managed SFWFiber 32 void spawn(T)(T _body) 33 if(is(T == voidDelegate) || is(T == voidFunction)) 34 { 35 if (stackSize > 0) 36 fibers ~= new SFWFiber(_body, stackSize); 37 else 38 fibers ~= new SFWFiber(_body); 39 } 40 41 /// create managed SFWFiber with infinity loop 42 void spawnInfLoop(T)(T loop_body) 43 if(is(T == voidDelegate) || is(T == voidFunction)) 44 { 45 spawn({ 46 while (true) 47 { 48 loop_body(); 49 yield(); 50 } 51 }); 52 } 53 54 /// set `work` to false and set exit_result 55 void exitLoop(int res=0) 56 { 57 work = false; 58 exit_result = res; 59 } 60 61 /// 62 int exitResult() nothrow const @property { return exit_result; } 63 64 /// while `work` call not terminate fibers 65 bool loop() 66 { 67 if (!work) return false; 68 fibers = fibers.filter!(f=>f.state != Fiber.State.TERM).array; 69 foreach (f; fibers) 70 if (f.nextTime < Clock.currStdTime) 71 f.call(); 72 return true; 73 } 74 }