1 /*
2  * Geario - A cross-platform abstraction library with asynchronous I/O.
3  *
4  * Copyright (C) 2021-2022 Kerisy.com
5  *
6  * Website: https://www.kerisy.com
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module geario.event.EventLoop;
13 
14 import geario.event.selector;
15 import geario.net.channel.Types;
16 import geario.logging;
17 import geario.util.worker;
18 
19 import core.thread;
20 import std.parallelism;
21 import std.random;
22 
23 /**
24  * 
25  */
26 final class EventLoop : AbstractSelector
27 {
28     this()
29     {
30         int id = uniform(0, 1024);
31         super(id, 1);
32     }
33 
34     this(Worker worker)
35     {
36         int id = uniform(0, 1024);
37         super(id, 1, worker);
38     }
39 
40     this(size_t id, size_t divider, Worker worker = null)
41     {
42         super(id, divider, worker);
43     }
44 
45     void StartLoop()
46     {
47         Run(timeout);
48     }
49     
50     override void Stop() {
51         if(IsStopping()) {
52             version (GEAR_IO_DEBUG) 
53             log.warn("The event loop %d is stopping.", GetId());
54             return;
55         }
56         
57         version (GEAR_IO_DEBUG) 
58         log.trace("Stopping event loop %d...", GetId());
59         if(IsSelfThread()) {
60             version (GEAR_IO_DEBUG) log.info("Try to stop the event loop %d in another thread", GetId());
61             auto stopTask = task(&Stop);
62             std.parallelism.taskPool.put(stopTask);
63         } else {
64             super.Stop();
65         }
66     }
67 }