1 /*
2  * Kiss - A refined core library for D programming language.
3  *
4  * Copyright (C) 2015-2018  Shanghai Putao Technology Co., Ltd
5  *
6  * Developer: HuntLabs.cn
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11  
12 module kiss.event.EventLoop;
13 
14 import kiss.event.core;
15 import kiss.event.selector;
16 import core.thread;
17 import kiss.event.task;
18 import kiss.exception;
19 
20 /**
21 
22 */
23 final class EventLoop : AbstractSelector
24 {
25 
26     this()
27     {
28         super();
29     }
30 
31     void run()
32     {
33         if (isRuning())
34             throw new LoopException("The current eventloop is running!");
35         _thread = Thread.getThis();
36         onLoop(&onWeakUp);
37     }
38 
39     override void stop()
40     {
41         _thread = null;
42         super.stop();
43     }
44 
45     bool isRuning()
46     {
47         return (_thread !is null);
48     }
49 
50     bool isInLoopThread()
51     {
52         return isRuning() && _thread is Thread.getThis();
53     }
54 
55     EventLoop postTask(AbstractTask task)
56     {
57         import kiss.logger;
58 
59         synchronized (this)
60         {
61             _queue.enQueue(task);
62         }
63         return this;
64     }
65 
66     static AbstractTask createTask(alias fun, Args...)(Args args)
67     {
68         return newTask!(fun, Args)(args);
69     }
70 
71     static AbstractTask createTask(F, Args...)(F delegateOrFp, Args args)
72             if (is(typeof(delegateOrFp(args))))
73     {
74         return newTask(F, Args)(delegateOrFp, args);
75     }
76 
77     protected void onWeakUp()
78     {
79         TaskQueue queue;
80         synchronized (this)
81         {
82             queue = _queue;
83             _queue = TaskQueue();
84         }
85         while (!queue.empty)
86         {
87             auto task = queue.deQueue();
88             task.job();
89         }
90     }
91 
92 private:
93     Thread _thread;
94     TaskQueue _queue;
95 }