Skip to content

Instantly share code, notes, and snippets.

@porterjamesj
Created October 28, 2014 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save porterjamesj/093c87c61115d154c683 to your computer and use it in GitHub Desktop.
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
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