1 /*******************************************************************************
2 
3     Utility to wrap any task and turn it into valid `ISuspendable`.
4 
5     Originally `Task` class itself was implementing `ISuspendable` but it had
6     to be removed because with current scheduler implementation it is not legal
7     for tasks to resume each other directly. Calling `suspend` is also only
8     legal from within the to-be-suspended task.
9 
10     `TaskSuspender` workarounds it by calling `delayedResume` instead on a
11     wrapped task and adding extra sanity checks about suspending context.
12 
13     Copyright:
14         Copyright (c) 2018 dunnhumby Germany GmbH.
15         All rights reserved.
16 
17     License:
18         Boost Software License Version 1.0. See LICENSE_BOOST.txt for details.
19         Alternatively, this file may be distributed under the terms of the Tango
20         3-Clause BSD License (see LICENSE_BSD.txt for details).
21 
22 *******************************************************************************/
23 
24 module ocean.task.util.TaskSuspender;
25 
26 import ocean.io.model.ISuspendable;
27 import ocean.task.Task;
28 import ocean.task.IScheduler;
29 import ocean.core.Verify;
30 
31 /// ditto
32 public class TaskSuspender : ISuspendable
33 {
34     private Task task;
35 
36     /***************************************************************************
37 
38         Constructor
39 
40         Params:
41             task = task instance to wrap as suspendable
42 
43     ***************************************************************************/
44 
45     public this ( Task task )
46     {
47         verify(task !is null);
48         this.task = task;
49     }
50 
51     /***************************************************************************
52 
53         Implements resuming as delayed resuming
54 
55     ***************************************************************************/
56 
57     override public void resume ( )
58     {
59         theScheduler.delayedResume(this.task);
60     }
61 
62     /***************************************************************************
63 
64         Forwards suspending to task while ensuring that it is called from
65         within the task context.
66 
67     ***************************************************************************/
68 
69     override public void suspend ( )
70     {
71         auto context = Task.getThis();
72         verify(context is this.task);
73         context.suspend();
74     }
75 
76     /***************************************************************************
77 
78         Returns:
79             task state (true if suspended)
80 
81     ***************************************************************************/
82 
83     override public bool suspended ( )
84     {
85         return this.task.suspended();
86     }
87 }