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;
17 import hunt.util.worker;
18 
19 import core.thread;
20 import std.parallelism;
21 import std.random;
22 
23 import core.atomic;
24 
25 /**
26  * 
27  */
28 final class EventLoop : AbstractSelector {
29 
30     private static shared int idCounter = 0;
31 
32     this() {
33         int id = atomicOp!("+=")(idCounter, 1);
34         super(id-1, 1);
35     }
36 
37     this(Worker worker) {
38         int id = atomicOp!("+=")(idCounter, 1);
39         super(id-1, 1, worker);
40     }
41 
42     this(size_t id, size_t divider, Worker worker = null) {
43         super(id, divider, worker);
44     }
45 
46     override void stop() {
47         if(isStopping()) {
48             version (HUNT_IO_DEBUG) 
49             warningf("The event loop %d is stopping.", getId());
50             return;
51         }
52         
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             version (HUNT_IO_DEBUG) 
59             warningf("Stopping event loop %d...", getId());
60             super.stop();
61         }
62     }
63 
64 }