SlideShare una empresa de Scribd logo
1 de 48
Concurrency in Julia
Julia Taiwan發起人 杜岳華
Outline
• Multitasking
• Concurrency
• Easy parallel
• Parallel computing
• Orchestration
Multitasking
Task
• Aka coroutine
• 類似function,但是可以執行到一半中斷並回傳值,去執行別的Task
julia> f(x) = println(x + 10)
julia> task = Task(f) # no argument
julia> task2 = @task f(2)
Task
julia> task2
Task (runnable) @0x00007fdab2199f90
julia> yield(task2)
12
julia> task2
Task (done) @0x00007fdab2199f90
Main() task2
yield(task2)
Task
• 與function不同:
• 切換task並不使用其他空間,只會使用存在的process的空間
• CPU不會意識到task的存在,不會做context switch
• Task之間的切換可以是任意順序
Single task
julia> function print_to(n)
for i in 1:n
println(i)
end
end
print_to (generic function with 1 method)
julia> foo = @task print_to(100)
Task (runnable)
Single task
julia> yield(foo)
1
2
3
…
100
julia> foo
Task (done)
Use wait() to pause
julia> function print_to(n)
for i in 1:n
println(i)
wait() # set task state
to :waiting and pause
end
end
print_to (generic function with 1 method)
julia> foo = @task print_to(100)
Task (runnable)
Use wait() to pause
julia> yield(foo)
1
julia> yield(foo)
2
julia> yield(foo)
3
julia> foo
Task (runnable)
Scheduling
function i_print_to(i, n)
for j in 1:n
println(“Task $(i) print $(j)”)
yield() # switch to scheduler
end
end
Scheduling
• @schedule: wrap expression as a Task and add to scheduler
@schedule i_print_to(1, 10)
@schedule i_print_to(2, 5)
@schedule i_print_to(3, 30)
Scheduling
Task 1 print 1
Task 2 print 1
Task 3 print 1
Task 1 print 2
Task 2 print 2
Task 3 print 2
Task 1 print 3
…
Task 2 Task 3scheduler Task 1
yield()
yield()
yield()
Task state
:runnable
:waiting
:queued :failed
:done
Multitasking
Task 2 Task 3scheduler Task 1
id = 1
yield(task1)
yield()
yield()
yield(task2)
yield(task3)
Concurrency
Concurrency
• A way of flow control
• A way to program
• Concurrency is about dealing with lots of things at once.
• Parallelism is about doing lots of things at once.
• Concurrency is not parallelism -- Rob Pike
Concurrency
Communicating Sequential Processes
• 善用Task及Channel
• 避免用Shared Array,或是其他share state objects
• 避免race condition
• 避免deadlock
• 不需要lock or synchronization
take!
put!
take!
take!
put!
put!
Communicating Sequential Processes
task
task
task
task
Channel
• Inter-task communication
• Synchronous (blocking)
ch = Channel{Int64}(50)
put!(ch, 5)
x = take!(ch)
isready(ch) # test if anything in it
close(ch)
Channel
open take!put!
closed take!
Channel is iterable
ch = Channel{Int64}(100)
for i in 1:100
put!(ch, i)
end
for i in ch
println(i)
end
Producer-consumer model
put!
task
take! task
task
task
task
task
Channel can be accessed by multi-task
function producer(ch)
for i in 1:100
put!(ch, i)
yield()
end
end
function consumer(ch)
while true
x = take!(ch)
println(x)
yield()
end
end
ch = Channel{Int64}(100)
for _ in 1:10
@schedule producer(ch)
@schedule consumer(ch)
end
Concurrency example
function f1(ch1)
for i in 1:100
put!(ch1, i)
end
end
function f2(ch1, ch2)
while true
x = take!(ch1)
y = x^2 + 1
put!(ch2, y)
yield()
end
end
ch1 = Channel{Int64}(100)
ch2 = Channel{Int64}(100)
ch3 = Channel{Tuple}(100)
function f3(ch2, ch3)
while true
x = take!(ch2)
y = log(x)
put!(ch3, (x, y))
yield()
end
end
You can bind channel to task
• Binding the lifetime of channel to specific task
• When a channel is bound to multiple tasks, the first task to terminate
will close the channel
t1 = @schedule f1(ch1)
t2 = @schedule f2(ch1, ch2)
t3 = @schedule f3(ch2, ch3)
bind(ch1, t1) # Optional
bind(ch2, t2)
bind(ch3, t3)
Concurrency example
• @async
• wrap expression as a Task
• put it to the scheduling queue
• adds it to the nearest enclosing set that @sync
waits for
• @sync
• Wait for all enclosed uses of @async, @spawn,
@spawnat and @parallel are complete
@sync begin
@async f1(ch1)
@async f2(ch1, ch2)
@async f3(ch2, ch3)
end
macro tips
• @task
• wrap expression as a Task
• @schedule
• wrap expression as a Task
• put it to the scheduling queue
• @async
• wrap expression as a Task
• put it to the scheduling queue
• adds it to the nearest enclosing set that @sync waits for
Events
cond = Condition()
function waiter(cond)
while true
x = wait(cond) # task
change state to :waiting
# do something
yield()
end
end
function notifyer(cond)
while true
x = f()
notify(cond, x) # change
waiter state to queued and pass x
to waiter
yield()
end
end
Easy parallel
Easy parallel
• Julia提供了非常簡單的parallel介面
• Julia的parallel primitives設計成類似於function call的方式
future = remotecall(rand, 2, 1000, 1000)
result = fetch(future)
@spawn
future = @spawnat 2 rand(1000, 1000)
result = fetch(future)
future = @spawn rand(1000, 1000)
result = fetch(future)
future = remotecall(rand, 2, 1000, 1000)
result = fetch(future)
Remote API
• remotecall(f, proc_id, args; kwargs) -> Future
• call function asynchronously
• remotecall_fetch(f, proc_id, args; kwargs)
• fetch(remotecall()), context switch
• remotecall_wait(f, proc_id, args; kwargs)
• wait(remotecall())
• remote_do(f, proc_id, args; kwargs) -> Void
• call function asynchronously but return nothing
Code accessibility
• Code should be accessible on execution processes.
• `include(“Module.jl”)`: only load file into current process
• `using Module`: load module to every process, but is brought into scope only on
current process
• `@everywhere`: directly define expressions on all processes
@everywhere using Module
Data movement
• Explicitly
• fetch
• Implicitly
• @spawn
r = @spawn rand(2,2)
s = @spawn 1 .+ fetch(r)
results = fetch(s)
@everywhere x = 10
@spawn API
• @spawnat p expr -> Future
• Create a closure around the expression and run it on specified process
• @spawn expr -> Future
• Create a closure around the expression and run it on automatically-chosen
process
Parallel for loop
• Equally distribute tasks into worker processes
• Suitable for lightweight task but huge amount of iterations
@parallel for i in 1:10000
# do something
end
result = @parallel (+) for i in 1:10000
y = f(i)
y
end
results = @parallel (vcat) for i in 1:10000
y = f(i)
[y]
end
Parallel map
• Run each heavy_work(args) in a process
args = [i for i in 1:1000]
result = pmap(heavy_work, args)
Parallel computing
Parallel computing
• Only one process
• myid() == 1 is also a worker
• Multiple processes
• Worker
• myid() == 1 is not a worker process
Run tasks on worker processes
func = [f1, f2, f3]
@sync begin
for (i, f) in zip(workers(), func)
@async remotecall(f, i)
end
end
RemoteChannel is required
• Channel: use with in local process
• RemoteChannel: pass data to remote process
• Composed of RemoteRef and Channel
ch1 = RemoteChannel(() -> Channel{Int64}(32))
ch2 = RemoteChannel(() -> Channel{Int64}(32))
ch3 = RemoteChannel(() -> Channel{Int64}(32))
Future is a specialized RemoteChannel
id =
1
worker
Channel{Any}(1)
Channel{?}(?)
RemoteRef
RemoteRef
Future
RemoteChannel
Orchestration
Orchestration
Task 2 Task 3scheduler Task 1
id =
1
worker worker
Local Remote
Task 4
worker
ASYNCSYNC
ASYNC I/O
Which macro make tasks run remotely?
• Local
• @async
• Remote
• @spawn
• @spawnat
• Hybrid
• @parallel
Thank you for attention

Más contenido relacionado

La actualidad más candente

“Tasks” in NetLogo 5.0beta1
“Tasks” in NetLogo 5.0beta1“Tasks” in NetLogo 5.0beta1
“Tasks” in NetLogo 5.0beta1
SethTisue
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 

La actualidad más candente (20)

Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
 
Swift Tutorial 2
Swift Tutorial  2Swift Tutorial  2
Swift Tutorial 2
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
 
“Tasks” in NetLogo 5.0beta1
“Tasks” in NetLogo 5.0beta1“Tasks” in NetLogo 5.0beta1
“Tasks” in NetLogo 5.0beta1
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
 
functions of C++
functions of C++functions of C++
functions of C++
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic Programmer
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programming
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 

Similar a 20170714 concurrency in julia

The theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmerThe theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmer
Roman Elizarov
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
ankita44
 

Similar a 20170714 concurrency in julia (20)

Pivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro Bignyak
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Mit6 094 iap10_lec02
Mit6 094 iap10_lec02Mit6 094 iap10_lec02
Mit6 094 iap10_lec02
 
Python 5-迴圈-while
Python 5-迴圈-whilePython 5-迴圈-while
Python 5-迴圈-while
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
The theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmerThe theory of concurrent programming for a seasoned programmer
The theory of concurrent programming for a seasoned programmer
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
 
Functions12
Functions12Functions12
Functions12
 
Functions123
Functions123 Functions123
Functions123
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Iteration
IterationIteration
Iteration
 
Functional go
Functional goFunctional go
Functional go
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 
Codefreeze rus
Codefreeze rusCodefreeze rus
Codefreeze rus
 
Codefreeze eng
Codefreeze engCodefreeze eng
Codefreeze eng
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
 

Más de 岳華 杜

Más de 岳華 杜 (20)

[COSCUP 2023] 我的Julia軟體架構演進之旅
[COSCUP 2023] 我的Julia軟體架構演進之旅[COSCUP 2023] 我的Julia軟體架構演進之旅
[COSCUP 2023] 我的Julia軟體架構演進之旅
 
Julia: The language for future
Julia: The language for futureJulia: The language for future
Julia: The language for future
 
The Language for future-julia
The Language for future-juliaThe Language for future-julia
The Language for future-julia
 
20190907 Julia the language for future
20190907 Julia the language for future20190907 Julia the language for future
20190907 Julia the language for future
 
Metaprogramming in julia
Metaprogramming in juliaMetaprogramming in julia
Metaprogramming in julia
 
Introduction to julia
Introduction to juliaIntroduction to julia
Introduction to julia
 
自然語言處理概覽
自然語言處理概覽自然語言處理概覽
自然語言處理概覽
 
Introduction to machine learning
Introduction to machine learningIntroduction to machine learning
Introduction to machine learning
 
Semantic Segmentation - Fully Convolutional Networks for Semantic Segmentation
Semantic Segmentation - Fully Convolutional Networks for Semantic SegmentationSemantic Segmentation - Fully Convolutional Networks for Semantic Segmentation
Semantic Segmentation - Fully Convolutional Networks for Semantic Segmentation
 
Batch normalization 與他愉快的小伙伴
Batch normalization 與他愉快的小伙伴Batch normalization 與他愉快的小伙伴
Batch normalization 與他愉快的小伙伴
 
從 VAE 走向深度學習新理論
從 VAE 走向深度學習新理論從 VAE 走向深度學習新理論
從 VAE 走向深度學習新理論
 
COSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in JuliaCOSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in Julia
 
COSCUP: Metaprogramming in Julia
COSCUP: Metaprogramming in JuliaCOSCUP: Metaprogramming in Julia
COSCUP: Metaprogramming in Julia
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia
 
20180506 Introduction to machine learning
20180506 Introduction to machine learning20180506 Introduction to machine learning
20180506 Introduction to machine learning
 
20171127 當julia遇上資料科學
20171127 當julia遇上資料科學20171127 當julia遇上資料科學
20171127 當julia遇上資料科學
 
20171117 oop and design patterns in julia
20171117 oop and design patterns in julia20171117 oop and design patterns in julia
20171117 oop and design patterns in julia
 
20171014 tips for manipulating filesystem in julia
20171014 tips for manipulating filesystem in julia20171014 tips for manipulating filesystem in julia
20171014 tips for manipulating filesystem in julia
 
20170807 julia的簡單而高效資料處理
20170807 julia的簡單而高效資料處理20170807 julia的簡單而高效資料處理
20170807 julia的簡單而高效資料處理
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

20170714 concurrency in julia

  • 1. Concurrency in Julia Julia Taiwan發起人 杜岳華
  • 2. Outline • Multitasking • Concurrency • Easy parallel • Parallel computing • Orchestration
  • 4. Task • Aka coroutine • 類似function,但是可以執行到一半中斷並回傳值,去執行別的Task julia> f(x) = println(x + 10) julia> task = Task(f) # no argument julia> task2 = @task f(2)
  • 5. Task julia> task2 Task (runnable) @0x00007fdab2199f90 julia> yield(task2) 12 julia> task2 Task (done) @0x00007fdab2199f90 Main() task2 yield(task2)
  • 6. Task • 與function不同: • 切換task並不使用其他空間,只會使用存在的process的空間 • CPU不會意識到task的存在,不會做context switch • Task之間的切換可以是任意順序
  • 7. Single task julia> function print_to(n) for i in 1:n println(i) end end print_to (generic function with 1 method) julia> foo = @task print_to(100) Task (runnable)
  • 9. Use wait() to pause julia> function print_to(n) for i in 1:n println(i) wait() # set task state to :waiting and pause end end print_to (generic function with 1 method) julia> foo = @task print_to(100) Task (runnable)
  • 10. Use wait() to pause julia> yield(foo) 1 julia> yield(foo) 2 julia> yield(foo) 3 julia> foo Task (runnable)
  • 11. Scheduling function i_print_to(i, n) for j in 1:n println(“Task $(i) print $(j)”) yield() # switch to scheduler end end
  • 12. Scheduling • @schedule: wrap expression as a Task and add to scheduler @schedule i_print_to(1, 10) @schedule i_print_to(2, 5) @schedule i_print_to(3, 30)
  • 13. Scheduling Task 1 print 1 Task 2 print 1 Task 3 print 1 Task 1 print 2 Task 2 print 2 Task 3 print 2 Task 1 print 3 … Task 2 Task 3scheduler Task 1 yield() yield() yield()
  • 15. Multitasking Task 2 Task 3scheduler Task 1 id = 1 yield(task1) yield() yield() yield(task2) yield(task3)
  • 17. Concurrency • A way of flow control • A way to program • Concurrency is about dealing with lots of things at once. • Parallelism is about doing lots of things at once. • Concurrency is not parallelism -- Rob Pike
  • 19. Communicating Sequential Processes • 善用Task及Channel • 避免用Shared Array,或是其他share state objects • 避免race condition • 避免deadlock • 不需要lock or synchronization take! put! take! take! put! put!
  • 21. Channel • Inter-task communication • Synchronous (blocking) ch = Channel{Int64}(50) put!(ch, 5) x = take!(ch) isready(ch) # test if anything in it close(ch)
  • 23. Channel is iterable ch = Channel{Int64}(100) for i in 1:100 put!(ch, i) end for i in ch println(i) end
  • 25. Channel can be accessed by multi-task function producer(ch) for i in 1:100 put!(ch, i) yield() end end function consumer(ch) while true x = take!(ch) println(x) yield() end end ch = Channel{Int64}(100) for _ in 1:10 @schedule producer(ch) @schedule consumer(ch) end
  • 26. Concurrency example function f1(ch1) for i in 1:100 put!(ch1, i) end end function f2(ch1, ch2) while true x = take!(ch1) y = x^2 + 1 put!(ch2, y) yield() end end ch1 = Channel{Int64}(100) ch2 = Channel{Int64}(100) ch3 = Channel{Tuple}(100) function f3(ch2, ch3) while true x = take!(ch2) y = log(x) put!(ch3, (x, y)) yield() end end
  • 27. You can bind channel to task • Binding the lifetime of channel to specific task • When a channel is bound to multiple tasks, the first task to terminate will close the channel t1 = @schedule f1(ch1) t2 = @schedule f2(ch1, ch2) t3 = @schedule f3(ch2, ch3) bind(ch1, t1) # Optional bind(ch2, t2) bind(ch3, t3)
  • 28. Concurrency example • @async • wrap expression as a Task • put it to the scheduling queue • adds it to the nearest enclosing set that @sync waits for • @sync • Wait for all enclosed uses of @async, @spawn, @spawnat and @parallel are complete @sync begin @async f1(ch1) @async f2(ch1, ch2) @async f3(ch2, ch3) end
  • 29. macro tips • @task • wrap expression as a Task • @schedule • wrap expression as a Task • put it to the scheduling queue • @async • wrap expression as a Task • put it to the scheduling queue • adds it to the nearest enclosing set that @sync waits for
  • 30. Events cond = Condition() function waiter(cond) while true x = wait(cond) # task change state to :waiting # do something yield() end end function notifyer(cond) while true x = f() notify(cond, x) # change waiter state to queued and pass x to waiter yield() end end
  • 32. Easy parallel • Julia提供了非常簡單的parallel介面 • Julia的parallel primitives設計成類似於function call的方式 future = remotecall(rand, 2, 1000, 1000) result = fetch(future)
  • 33. @spawn future = @spawnat 2 rand(1000, 1000) result = fetch(future) future = @spawn rand(1000, 1000) result = fetch(future) future = remotecall(rand, 2, 1000, 1000) result = fetch(future)
  • 34. Remote API • remotecall(f, proc_id, args; kwargs) -> Future • call function asynchronously • remotecall_fetch(f, proc_id, args; kwargs) • fetch(remotecall()), context switch • remotecall_wait(f, proc_id, args; kwargs) • wait(remotecall()) • remote_do(f, proc_id, args; kwargs) -> Void • call function asynchronously but return nothing
  • 35. Code accessibility • Code should be accessible on execution processes. • `include(“Module.jl”)`: only load file into current process • `using Module`: load module to every process, but is brought into scope only on current process • `@everywhere`: directly define expressions on all processes @everywhere using Module
  • 36. Data movement • Explicitly • fetch • Implicitly • @spawn r = @spawn rand(2,2) s = @spawn 1 .+ fetch(r) results = fetch(s) @everywhere x = 10
  • 37. @spawn API • @spawnat p expr -> Future • Create a closure around the expression and run it on specified process • @spawn expr -> Future • Create a closure around the expression and run it on automatically-chosen process
  • 38. Parallel for loop • Equally distribute tasks into worker processes • Suitable for lightweight task but huge amount of iterations @parallel for i in 1:10000 # do something end result = @parallel (+) for i in 1:10000 y = f(i) y end results = @parallel (vcat) for i in 1:10000 y = f(i) [y] end
  • 39. Parallel map • Run each heavy_work(args) in a process args = [i for i in 1:1000] result = pmap(heavy_work, args)
  • 41. Parallel computing • Only one process • myid() == 1 is also a worker • Multiple processes • Worker • myid() == 1 is not a worker process
  • 42. Run tasks on worker processes func = [f1, f2, f3] @sync begin for (i, f) in zip(workers(), func) @async remotecall(f, i) end end
  • 43. RemoteChannel is required • Channel: use with in local process • RemoteChannel: pass data to remote process • Composed of RemoteRef and Channel ch1 = RemoteChannel(() -> Channel{Int64}(32)) ch2 = RemoteChannel(() -> Channel{Int64}(32)) ch3 = RemoteChannel(() -> Channel{Int64}(32))
  • 44. Future is a specialized RemoteChannel id = 1 worker Channel{Any}(1) Channel{?}(?) RemoteRef RemoteRef Future RemoteChannel
  • 46. Orchestration Task 2 Task 3scheduler Task 1 id = 1 worker worker Local Remote Task 4 worker ASYNCSYNC ASYNC I/O
  • 47. Which macro make tasks run remotely? • Local • @async • Remote • @spawn • @spawnat • Hybrid • @parallel
  • 48. Thank you for attention