1 /*******************************************************************************
2 
3     Simple utility to run a delegate inside a task while automatically starting
4     event loop behind the scen. Intended for usage in script-like programs, does
5     a new allocation each call.
6 
7     Copyright:
8         Copyright (c) 2018 dunnhumby Germany GmbH.
9         All rights reserved.
10 
11     License:
12         Boost Software License Version 1.0. See LICENSE_BOOST.txt for details.
13         Alternatively, this file may be distributed under the terms of the Tango
14         3-Clause BSD License (see LICENSE_BSD.txt for details).
15 
16 *******************************************************************************/
17 
18 module ocean.task.util.QuickRun;
19 
20 import ocean.task.IScheduler;
21 import ocean.task.Task;
22 import ocean.core.Verify;
23 
24 /*******************************************************************************
25 
26     Turns `dg` into a task and runs it through scheduler. Starts the event loop
27     automatically and will finish only when all tasks finish and no registered
28     events remain (or `theScheduler.shutdown` is called).
29 
30     Requires `initScheduler` to be already called before.
31 
32     Params:
33         dg = delegate to run inside a task. Return value of the delegate will
34             be propagated as the return value of `quickRun` itself, which can
35             used as app exit status code.
36 
37 *******************************************************************************/
38 
39 public int quickRun ( scope int delegate () dg )
40 {
41     auto task = new DgTask(dg);
42     theScheduler.queue(task);
43     theScheduler.eventLoop();
44     verify(task.finished());
45     return task.result;
46 }
47 
48 ///
49 unittest
50 {
51     int main ( )
52     {
53         // Make sure the scheduler is initialized first, e.g.:
54         // initScheduler(SchedulerConfiguration.init);
55 
56         return quickRun({
57             // code that has to run inside task
58             return 42;
59         });
60     }
61 }
62 
63 /*******************************************************************************
64 
65     Helper to turn a delegate into a task.
66 
67 *******************************************************************************/
68 
69 private class DgTask : Task
70 {
71     int delegate () dg;
72     int result;
73 
74     this (scope int delegate() dg)
75     {
76         this.dg = dg;
77     }
78 
79     override void run ()
80     {
81         this.result = this.dg();
82     }
83 }