Skip to content

Instantly share code, notes, and snippets.

@felipenoris
Last active November 29, 2020 14:50
Show Gist options
  • Save felipenoris/10e135bf6dcb0298057762146b4104e2 to your computer and use it in GitHub Desktop.
Save felipenoris/10e135bf6dcb0298057762146b4104e2 to your computer and use it in GitHub Desktop.
# implements `run_notify_action(listener, val=nothing)`
abstract type AbstractEventListener end
# makes `listener` listen to notify events on `condition`
function add_listener(condition::Threads.Condition, listener::AbstractEventListener)
Threads.@spawn begin
lock(condition)
try
while true
val = wait(condition)
run_notify_action(listener, val)
end
finally
# if something goes wrong,
# `listener` will stop listening
# to this condition
unlock(condition)
end
end
end
function notify_listeners(condition::Threads.Condition, val=nothing)
lock(condition)
try
notify(condition, val)
finally
unlock(condition)
end
end
#
# Dummy Implementation
#
struct MyListener <: AbstractEventListener
name::String
end
# implements AbstractEventListener interface for MyListener
function run_notify_action(listener::MyListener, val=nothing)
@info("Listener $(listener.name) was notified with val = $val")
end
#
# Example program
#
# a condition for listeners to listen on
const LISTENERS_CONDITION = Threads.Condition()
# registers a few listeners
add_listener(LISTENERS_CONDITION, MyListener("Listener 1"))
add_listener(LISTENERS_CONDITION, MyListener("Listener 2"))
# wakes up listeners
notify_listeners(LISTENERS_CONDITION, "hey you out there")
# Output
#=
┌ Info: Listener Listener 1 was notified with val = hey you out there
└ @ Main In[4]:8
┌ Info: Listener Listener 2 was notified with val = hey you out there
└ @ Main In[4]:8
=#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment