SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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 FreeLuka Jacobowitz
 
Swift Tutorial 2
Swift Tutorial  2Swift Tutorial  2
Swift Tutorial 2Jintin Lin
 
Queue implementation
Queue implementationQueue implementation
Queue implementationRajendran
 
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”Platonov Sergey
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguageSamir Chekkal
 
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 languageSQLI
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.lnikolaeva
 
“Tasks” in NetLogo 5.0beta1
“Tasks” in NetLogo 5.0beta1“Tasks” in NetLogo 5.0beta1
“Tasks” in NetLogo 5.0beta1SethTisue
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
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 181Mahmoud Samir Fayed
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 
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 WebGLLuka Jacobowitz
 
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 ProgrammerRaúl Raja Martínez
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
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 programmingLukasz Dynowski
 
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 2015Leonardo Borges
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 

Was ist angesagt? (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 }
 

Ähnlich wie Concurrency in Julia: Easy Parallel and Orchestration Techniques

Pivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak MeetUp
 
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 CompletableFuturesHaim Yadid
 
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 programmerRoman Elizarov
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functionsankita44
 
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 NLArie Leeuwesteijn
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
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...Data Con LA
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Ziyauddin Shaik
 
Codefreeze rus
Codefreeze rusCodefreeze rus
Codefreeze rusDevexperts
 
Codefreeze eng
Codefreeze engCodefreeze eng
Codefreeze engDevexperts
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordKit Eason
 

Ähnlich wie Concurrency in Julia: Easy Parallel and Orchestration Techniques (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
 

Mehr von 岳華 杜

[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的簡單而高效資料處理岳華 杜
 

Mehr von 岳華 杜 (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的簡單而高效資料處理
 

Kürzlich hochgeladen

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Kürzlich hochgeladen (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Concurrency in Julia: Easy Parallel and Orchestration Techniques

  • 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