forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.jl
345 lines (293 loc) · 9.78 KB
/
event.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# This file is a part of Julia. License is MIT: http:https://julialang.org/license
## condition variables
type Condition
waitq::Vector{Any}
Condition() = new([])
end
function wait(c::Condition)
ct = current_task()
push!(c.waitq, ct)
try
return wait()
catch
filter!(x->x!==ct, c.waitq)
rethrow()
end
end
notify(c::Condition, arg::ANY=nothing; all=true, error=false) = notify(c, arg, all, error)
function notify(c::Condition, arg, all, error)
if all
for t in c.waitq
schedule(t, arg, error=error)
end
empty!(c.waitq)
elseif !isempty(c.waitq)
t = shift!(c.waitq)
schedule(t, arg, error=error)
end
nothing
end
notify1(c::Condition, arg=nothing) = notify(c, arg, all=false)
notify_error(c::Condition, err) = notify(c, err, error=true)
notify1_error(c::Condition, err) = notify(c, err, error=true, all=false)
# schedule an expression to run asynchronously, with minimal ceremony
macro schedule(expr)
expr = :(()->($expr))
:(enq_work(Task($(esc(expr)))))
end
## scheduler and work queue
global const Workqueue = Any[]
function enq_work(t::Task)
t.state == :runnable || error("schedule: Task not runnable")
ccall(:uv_stop, Void, (Ptr{Void},), eventloop())
push!(Workqueue, t)
t.state = :queued
return t
end
schedule(t::Task) = enq_work(t)
function schedule(t::Task, arg; error=false)
# schedule a task to be (re)started with the given value or exception
if error
t.exception = arg
else
t.result = arg
end
return enq_work(t)
end
# fast version of schedule(t,v);wait()
function schedule_and_wait(t::Task, v=nothing)
t.state == :runnable || error("schedule: Task not runnable")
if isempty(Workqueue)
return yieldto(t, v)
else
t.result = v
push!(Workqueue, t)
t.state = :queued
end
return wait()
end
yield() = (enq_work(current_task()); wait())
yieldto(t::Task, x::ANY = nothing) = ccall(:jl_switchto, Any, (Any, Any), t, x)
# yield to a task, throwing an exception in it
function throwto(t::Task, exc)
t.exception = exc
yieldto(t)
end
function wait()
while true
if isempty(Workqueue)
c = process_events(true)
if c==0 && eventloop()!=C_NULL && isempty(Workqueue)
# if there are no active handles and no runnable tasks, just
# wait for signals.
pause()
end
else
t = shift!(Workqueue)
if t.state != :queued
# assume this somehow got queued twice,
# probably broken now, but try discarding this switch and keep going
# can't throw here, because it's probably not the fault of the caller to wait
# and don't want to use print() here, because that may try to incur a task switch
ccall(:jl_safe_printf, Void, (Ptr{UInt8}, Vararg{Int32}),
"\nWARNING: Workqueue inconsistency detected: shift!(Workqueue).state != :queued\n")
continue
end
arg = t.result
t.result = nothing
t.state = :runnable
local result
try
result = yieldto(t, arg)
current_task().state == :runnable || throw(AssertionError("current_task().state == :runnable"))
catch e
ct = current_task()
if ct.state == :queued
if t.state == :runnable
# assume we failed to queue t
# return it to the queue to be scheduled later
t.result = arg
t.state = :queued
push!(Workqueue, t)
end
# return ourself to the runnable state
i = findfirst(Workqueue, ct)
i == 0 || deleteat!(Workqueue, i)
ct.state = :runnable
end
rethrow(e)
end
process_events(false)
# return when we come out of the queue
return result
end
end
assert(false)
end
if is_windows()
pause() = ccall(:Sleep, stdcall, Void, (UInt32,), 0xffffffff)
else
pause() = ccall(:pause, Void, ())
end
## async event notifications
"""
AsyncCondition()
Create a async condition that wakes up tasks waiting for it (by calling `wait` on the object)
when notified from C by a call to uv_async_send.
Waiting tasks are woken with an error when the object is closed (by `close`).
Use `isopen` to check whether it is still active.
"""
type AsyncCondition
handle::Ptr{Void}
cond::Condition
function AsyncCondition()
this = new(Libc.malloc(_sizeof_uv_async), Condition())
associate_julia_struct(this.handle, this)
preserve_handle(this)
err = ccall(:uv_async_init, Cint, (Ptr{Void}, Ptr{Void}, Ptr{Void}),
eventloop(), this, uv_jl_asynccb::Ptr{Void})
this
end
end
unsafe_convert(::Type{Ptr{Void}}, async::AsyncCondition) = async.handle
function wait(async::AsyncCondition)
isopen(async) || throw(EOFError())
wait(async.cond)
end
isopen(t::AsyncCondition) = (t.handle != C_NULL)
close(t::AsyncCondition) = ccall(:jl_close_uv, Void, (Ptr{Void},), t)
function _uv_hook_close(async::AsyncCondition)
async.handle = C_NULL
unpreserve_handle(async)
notify_error(async.cond, EOFError())
nothing
end
function uv_asynccb(handle::Ptr{Void})
async = @handle_as handle AsyncCondition
notify(async.cond)
nothing
end
"""
AsyncCondition(callback::Function)
Create a async condition that calls the given `callback` function. The `callback` is passed one argument,
the async condition object itself.
"""
function AsyncCondition(cb::Function)
async = AsyncCondition()
waiter = Task(function()
while isopen(async)
success = try
wait(async)
true
catch # ignore possible exception on close()
false
end
success && cb(async)
end
end)
# must start the task right away so that it can wait for the AsyncCondition before
# we re-enter the event loop. this avoids a race condition. see issue #12719
enq_work(current_task())
yieldto(waiter)
return async
end
## timer-based notifications
"""
Timer(delay, repeat=0)
Create a timer that wakes up tasks waiting for it (by calling `wait` on the timer object) at
a specified interval. Times are in seconds. Waiting tasks are woken with an error when the
timer is closed (by `close`). Use `isopen` to check whether a timer is still active.
"""
type Timer
handle::Ptr{Void}
cond::Condition
isopen::Bool
function Timer(timeout::Real, repeat::Real=0.0)
timeout ≥ 0 || throw(ArgumentError("timer cannot have negative timeout of $timeout seconds"))
repeat ≥ 0 || throw(ArgumentError("timer cannot have negative repeat interval of $repeat seconds"))
this = new(Libc.malloc(_sizeof_uv_timer), Condition(), true)
err = ccall(:uv_timer_init, Cint, (Ptr{Void}, Ptr{Void}), eventloop(), this)
if err != 0
#TODO: this codepath is currently not tested
Libc.free(this.handle)
this.handle = C_NULL
throw(UVError("uv_make_timer",err))
end
associate_julia_struct(this.handle, this)
preserve_handle(this)
ccall(:uv_update_time, Void, (Ptr{Void},), eventloop())
ccall(:uv_timer_start, Cint, (Ptr{Void}, Ptr{Void}, UInt64, UInt64),
this, uv_jl_timercb::Ptr{Void},
UInt64(round(timeout * 1000)) + 1, UInt64(round(repeat * 1000)))
return this
end
end
unsafe_convert(::Type{Ptr{Void}}, t::Timer) = t.handle
function wait(t::Timer)
isopen(t) || throw(EOFError())
wait(t.cond)
end
isopen(t::Timer) = t.isopen
function close(t::Timer)
if t.handle != C_NULL
t.isopen = false
ccall(:uv_timer_stop, Cint, (Ptr{Void},), t)
ccall(:jl_close_uv, Void, (Ptr{Void},), t)
end
nothing
end
function _uv_hook_close(t::Timer)
unpreserve_handle(t)
disassociate_julia_struct(t)
t.handle = C_NULL
t.isopen = false
notify_error(t.cond, EOFError())
nothing
end
function uv_timercb(handle::Ptr{Void})
t = @handle_as handle Timer
if ccall(:uv_timer_get_repeat, UInt64, (Ptr{Void},), t) == 0
# timer is stopped now
close(t)
end
notify(t.cond)
nothing
end
"""
sleep(seconds)
Block the current task for a specified number of seconds. The minimum sleep time is 1
millisecond or input of `0.001`.
"""
function sleep(sec::Real)
sec ≥ 0 || throw(ArgumentError("cannot sleep for $sec seconds"))
wait(Timer(sec))
nothing
end
# timer with repeated callback
"""
Timer(callback::Function, delay, repeat=0)
Create a timer to call the given `callback` function. The `callback` is passed one argument,
the timer object itself. The callback will be invoked after the specified initial `delay`,
and then repeating with the given `repeat` interval. If `repeat` is `0`, the timer is only
triggered once. Times are in seconds. A timer is stopped and has its resources freed by
calling `close` on it.
"""
function Timer(cb::Function, timeout::Real, repeat::Real=0.0)
t = Timer(timeout, repeat)
waiter = Task(function()
while isopen(t)
success = try
wait(t)
true
catch # ignore possible exception on close()
false
end
success && cb(t)
end
end)
# must start the task right away so that it can wait for the Timer before
# we re-enter the event loop. this avoids a race condition. see issue #12719
enq_work(current_task())
yieldto(waiter)
return t
end