Events: Difference between revisions

1,723 bytes added ,  5 years ago
No edit summary
Line 866:
 
See also [[Handle_a_signal#Perl_6]] for an example of using Supplies to do reactive programming based on events (Unix signals in this case).
 
=={{header|Phix}}==
The primary synchronisation primitive in phix is the critical section, in the following the leave_cs()
in main() acts as signalling an event, and the one in echo() from whichever goes first acts to signal
that the other can/should resume.
<lang Phix>constant lock = init_cs()
include timedate.e
 
procedure showtime()
puts(1,format_timedate(date()," h:m:s\n"))
end procedure
 
procedure echo(string s)
sleep(rnd()/10) -- see note
enter_cs(lock)
puts(1,s)
sleep(1)
showtime()
leave_cs(lock)
end procedure
 
procedure main()
enter_cs(lock)
sequence threads = {create_thread(routine_id("echo"),{"job1"}),
create_thread(routine_id("echo"),{"job2"})}
puts(1,"main")
showtime()
sleep(1)
puts(1,"free")
showtime()
leave_cs(lock)
wait_thread(threads)
puts(1,"done\n")
end procedure
main()</lang>
{{out}}
Typically the first thread to attempt enter_cs() is released first, but there is
no guarantee of that. The sleep(rnd()/10) above evens out the likelihood, by
pausing for up to 0.1s, but otherwise isn't necessary.
<pre>
main 10:00:57
free 10:00:58
job2 10:00:59
job1 10:01:00
done
</pre>
External events such as timers and user input are handled in pGUI, eg
<lang Phix>function timer_cb(Ihandle /*ih*/)
IupUpdate(canvas)
return IUP_IGNORE
end function
 
Ihandle timer = IupTimer(Icallback("timer_cb"), 1000)
 
function key_cb(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if
if c=K_F5 then
iteration = 0
IupSetInt(timer,"RUN",1) -- (restart timer)
end if
return IUP_CONTINUE
end function
 
IupSetCallback(dlg, "K_ANY", Icallback("key_cb"))</lang>
 
=={{header|PicoLisp}}==
7,805

edits