Created
October 28, 2014 17:34
-
-
Save porterjamesj/093c87c61115d154c683 to your computer and use it in GitHub Desktop.
demonstration that Julia task-switching happens only when a task has to wait on IO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function do_computation_then_print(message::String) | |
sum = 1 | |
for i = 1:(rand() * 10^7) | |
sum *= i | |
end | |
# print out the sum so the compiler doesn't elide the loop | |
print("$message: $sum\n") | |
end | |
function sleep_then_print(message::String) | |
sleep(2*rand()) | |
println(message) | |
end | |
function go() | |
println("Computation in task (deterministic)") | |
@sync begin | |
@async do_computation_then_print("hi!") | |
@async do_computation_then_print("hi again!") | |
@async do_computation_then_print("hi for a third time!") | |
end | |
println("Sleeping in task (random)") | |
@sync begin | |
@async sleep_then_print("hi!") | |
@async sleep_then_print("hi again!") | |
@async sleep_then_print("hi for a third time!") | |
end | |
end | |
go() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment