1+ # DTask-level cancellation
2+
3+ struct CancelToken
4+ cancelled:: Base.RefValue{Bool}
5+ event:: Base.Event
6+ end
7+ CancelToken () = CancelToken (Ref (false ), Base. Event ())
8+ function cancel! (token:: CancelToken )
9+ token. cancelled[] = true
10+ notify (token. event)
11+ return
12+ end
13+ is_cancelled (token:: CancelToken ) = token. cancelled[]
14+ Base. wait (token:: CancelToken ) = wait (token. event)
15+ # TODO : Enable this for safety
16+ # Serialization.serialize(io::AbstractSerializer, ::CancelToken) =
17+ # throw(ConcurrencyViolationError("Cannot serialize a CancelToken"))
18+
19+ const DTASK_CANCEL_TOKEN = TaskLocalValue {Union{CancelToken,Nothing}} (()-> nothing )
20+
21+ function clone_cancel_token_remote (orig_token:: CancelToken , wid:: Integer )
22+ remote_token = remotecall_fetch (wid) do
23+ return poolset (CancelToken ())
24+ end
25+ errormonitor_tracked (" remote cancel_token communicator" , Threads. @spawn begin
26+ wait (orig_token)
27+ @dagdebug nothing :cancel " Cancelling remote token on worker $wid "
28+ MemPool. access_ref (remote_token) do remote_token
29+ cancel! (remote_token)
30+ end
31+ end )
32+ end
33+
34+ # Global-level cancellation
35+
136"""
237 cancel!(task::DTask; force::Bool=false, halt_sch::Bool=false)
338
@@ -80,11 +115,11 @@ function _cancel!(state, tid, force, halt_sch)
80115 Tf === typeof (Sch. eager_thunk) && continue
81116 istaskdone (task) && continue
82117 any_cancelled = true
83- @dagdebug tid :cancel " Cancelling running task ($Tf )"
84118 if force
85119 @dagdebug tid :cancel " Interrupting running task ($Tf )"
86120 Threads. @spawn Base. throwto (task, InterruptException ())
87121 else
122+ @dagdebug tid :cancel " Cancelling running task ($Tf )"
88123 # Tell the processor to just drop this task
89124 task_occupancy = task_spec[4 ]
90125 time_util = task_spec[2 ]
@@ -93,6 +128,7 @@ function _cancel!(state, tid, force, halt_sch)
93128 push! (istate. cancelled, tid)
94129 to_proc = istate. proc
95130 put! (istate. return_queue, (myid (), to_proc, tid, (InterruptException (), nothing )))
131+ cancel! (istate. cancel_tokens[tid])
96132 end
97133 end
98134 end
0 commit comments