1 /*
2  * Hunt - A refined core library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.event.EventLoop;
13 
14 import hunt.event.selector;
15 import hunt.io.channel.Common;
16 import hunt.logging.ConsoleLogger;
17 import hunt.util.TaskPool;
18 
19 import core.thread;
20 import std.parallelism;
21 import std.random;
22 
23 alias HuntTaskPool = hunt.util.TaskPool.TaskPool;
24 
25 /**
26  * 
27  */
28 final class EventLoop : AbstractSelector {
29 
30     this() {
31         int id = uniform(0, 1024);
32         super(id, 1);
33     }
34 
35     this(HuntTaskPool pool) {
36         int id = uniform(0, 1024);
37         super(id, 1, pool);
38     }
39 
40     this(size_t id, size_t divider, HuntTaskPool pool = null) {
41         super(id, divider, pool);
42     }
43 
44     override void stop() {
45         if(isStopping()) {
46             version (HUNT_IO_DEBUG) 
47             warningf("The event loop %d is stopping.", getId());
48             return;
49         }
50         
51         version (HUNT_IO_DEBUG) 
52         tracef("Stopping event loop %d...", getId());
53         if(isSelfThread()) {
54             version (HUNT_IO_DEBUG) infof("Try to stop the event loop %d in another thread", getId());
55             auto stopTask = task(&stop);
56             std.parallelism.taskPool.put(stopTask);
57         } else {
58             super.stop();
59         }
60     }
61 
62 }