SlideShare ist ein Scribd-Unternehmen logo
1 von 55
Downloaden Sie, um offline zu lesen
Fiber in the
10th year
Koichi Sasada
ko1@cookpad.com
About this talk
•Behavior of Fiber
•History of Fiber
•Implementation of Fiber
•Auto Fiber proposal
Koichi Sasada
http://atdot.net/~ko1/
•A programmer
•2006-2012 Faculty
•2012-2017 Heroku, Inc.
•2017- Cookpad Inc.
•Job: MRI development
•Core parts
•VM, Threads, GC, etc
Fiber
User-defined context switching
Fiber example
Infinite generator
fib = Fiber.new do
Fiber.yield a = b = 1
loop{ a, b = b, a+b
Fiber.yield a }
end
10.times{ p fib.resume }
Fiber example
Infinite generator
fib = Fiber.new do
Fiber.yield a = b = 1
loop{ a, b = b, a+b
Fiber.yield a }
end
10.times{ p fib.resume }
1. Fiber creation
2. Resume Fiber
3. Return to the
parent fiber
4. Resume fiber
(again)
5. Return to the
parent fiber
6. Resume fiber
(again2)
Fiber example
Infinite generator
fib = Fiber.new do
Fiber.yield a = b = 1
loop{ a, b = b, a+b
Fiber.yield a }
end
10.times{ p fib.resume }
1. Fiber creation
2. Resume Fiber
3. Return to the
parent fiber
4. Resume fiber
(again)
5. Return to the
parent fiber
6. Resume fiber
(again2)
Not a Proc?
a = 0; b = 1
fib = Proc.new{
a, b = b, a+b
a
}
p fib.call #=> 1
p fib.call #=> 1
p fib.call #=> 2
p fib.call #=> 3
p fib.call #=> 5
Proc can’t restart from
the middle of block
Proc (method) v.s. Fiber
Proc (method) Fiber
Start OK: call OK: Fiber#resume
Parameters OK: block (method) parameters OK: block parameters
Return OK: exit Proc/method OK: exit Proc/method
Suspend NG: N/A OK: Fiber.yield
Continue NG: N/A OK: Fiber#resume
Fiber example
Inner iterator to external iterator
f1 = Fiber.new do
2.times{|i| Fiber.yield i}
end
p f1.resume #=> 0
p f1.resume #=> 1
p f1.resume #=> 2 # return value of #times
p f1.resume #=> dead fiber called
(FiberError)
Fiber example
Inner iterator to external iterator
etc_passwd_ex_iter = Fiber.new do
open('/etc/passwd').each_line{|line|
Fiber.yield line
}
end
p etc_passwd_ex_iter.resume #=> 1st line
p etc_passwd_ex_iter.resume #=> 2nd line
…
Fiber example
Inner iterator to external iterator
# make Enumerator
iter = open('/etc/passwd').each_line
# Enumerator#next use Fiber implicitly
p iter.next #=> 1st line
p iter.next #=> 2nd line
…
Fiber example
Agent simulation
characters << Fiber.new{
loop{cat.move_up; Fiber.yield}}
characters << Fiber.new{
loop{dog.move_left; Fiber.yield}}
…
loop{cs.each{|e| e.resume}; redraw}
Fiber example
Agent simulation
characters << Fiber.new{
# you can specify complex rule for chars
loop{
cow.move_up; Fiber.yield
cow.move_right; Fiber.yield
cow.move_down; Fiber.yield
cow.move_left; Fiber.yield
}
}
Fiber example
Non-blocking IO scheduler
Wait multiple IO ops with
traditional “select” or
modern “poll”, “epoll” interface
Not a Thread?
Thread Fiber
Suspend/continue Yes Yes
Switch on timer Yes No (explicit switch)
Switch on I/O blocking Yes No (explicit switch)
Synchronization Required Not required
Specify next context No Yes
Performance: Creation Heavy Lightweight
Performance: Switch Lightweight Heavy (initial version)
Lightweight (now)
Brief History of Fibers
Fiber: Brief history
•2007/05/23 cont.c (for callcc)
•2007/05/25 Fiber impl. [ruby-dev:30827]
•2007/05/28 Fiber introduced into cont.c
•2007/08/25 Fix Fiber spec
Background: Callcc and Fiber on Ruby 1.9
• 2007/01 YARV was merged without “callcc”
• Biggest usage of “callcc” is for “Generator”
• Convert an internal iterator to an external iterator
• Usually one-shot continuation is required
→ Coroutine is enough for this purpose
• Capturing continuation (callcc) is heavy operation
• Implementation is easy because we can refer Ruby 1.8 user-level
threads
• 2007/05/?? I was introduced one paper something like generator
for (maybe) C# (so I began to consider about this feature)
• And I have a spare time at academic conference
2007/05/22 IRC log
(seeing a blog post)
00:56:49 <ko1> うーむ,callcc 欲しいっすか
English: Umm, do you want “callcc”?
2007/05/23 cont.c
2007/05/23 IRC log
(nobu pointed out there are several bugs on callcc)
12:15:36 <ko1> callcc 禁止でいいよ
EN: callcc should be prohibited
12:15:52 <ko1> これ作りながら,Fiber作ったほうが
速いなーとか思って亜
EN: Building callcc, I’m thinking that making Fiber
is more straightforward.
Fiber naming
•The name “Fiber” is from Windows API
• “A fiber is a unit of execution that must be manually
scheduled by the application. Fibers run in the context
of the threads that schedule them. Each thread can
schedule multiple fibers. In general, fibers do not
provide advantages over a well-designed
multithreaded application. However, using fibers can
make it easier to port applications that were designed
to schedule their own threads.”
https://msdn.microsoft.com/ja-
jp/library/windows/desktop/ms682661(v=vs.85).aspx
[ruby-dev:30828] Re: Supporting Fiber
Naming of Fiber
“Fiberでいいんじゃないでしょうか。
何かかっこいいですよね。” by shugo
EN: “I’m ok the name of “Fiber”.
Somewhat cool.” by shugo
2007/05/28 Introduction
r13295, [ruby-dev:30827]
First Fiber is Coroutine
Fiber#pass
f1 = Fiber.new{
f2.pass; f2.pass}
f2 = Fiber.new{
f3.pass}
f3 = Fiber.new{
f1.pass}
f1.pass
No parents/children
All routines are equivalent
Co-operative routines
= Coroutine
NOTE: renamed to “Fiber#transfer” now
Fiber#pass → Fiber#yield
[ruby-dev:30847] Re: Supporting Fiber
Matz’s idea
Coroutine or Semi-coroutine
•Coroutine is difficult
• You need to manage all transitions of Fibers
• Remember that most of languages have only “routine”
(not “co-”) and it is easy to use.
• Most of case, semi-coroutine is easy and enough
• Exception handling
• On semi-croutine, exceptions are raised to the parent
Fiber(s)
• Maybe it has critical BUG issue.
•Coroutine is powerful
• No limitation (a bit old-language constructs)
[ruby-dev:31583] Fiber reviesed
Semi-coroutine (Fiber) and Coroutine (Fiber::Core)
2007/08/25 IRC log
10:26:49 <ko1> 大クラス主義ならFiber に Semi も Coroutine
も機能いっしょくたにするべきかなあ
EN: Semi- and non-semi Coroutine may be
in one class undr big class principle
10:32:15 <ko1> というわけで,いっしょくたにしてみる
EN: So that I merged it.
* It was just idea in two lines…
Fiber::Core was removed
Commit message does not work well…
Final specification of Fiber
• Semi-coroutine
• Fiber#resume and Fiber.yield
• Make parent and child relationship (tree)
• Prohibit double resume
• Coroutine
• Fiber#transfer
• Prohibt to call semi-coroutine methods
on “transfer”ed fiber (coroutine)
fib1
(parent)
fib2
(child/parent)
fib3
(child)
resume
resume
double resume
is prohibited
NG!!
Implementation of Fibers
Implementation history
(1) 2007/05 Copy all machine stack
(2) 2010/05 FIBER_USE_NATIVE
(3) 2017/09 Switch only pointer
Fiber context representation
•Context:
•Thread states (current program counter, etc)
•VM stack
•Machine stack
•“Context switching” means exchange
contexts
Fiber implementation
2007 (1) Copy machine stack
•Store and restore “Context” by copying
machine stack
machine
stack area
machine
stack of fib1
machine
stack of fib2
Store
Restore
Switch from
running fib1 to
suspended fib2
Fiber implementation
2007 (1) Copy machine stack
•Good
•Same idea of a Ruby 1.8
user-level thread code
•Not so many memory usage
•Almost portable
•Bad
•Copy time is relative to
stack-depth (O(N))
machine
stack area
machine
stack of fib1
machine
stack of fib2
Store
Restore
Fiber implementation
2010 (2) Use Native support
•Switch machine stack by system APIs
•Supported APIs
•POSIX makecontext/setcontext
•Win32 Fiber API
•Machine stack exchange is only pointer
exchange (O(1))
•Implemented by Mr. Shiba (with me)
“A Fast Fiber Implementation for Ruby 1.9”
“Ruby1.9での高速なFiberの実装”,
第51回プログラミング・シンポジウム予稿集, pp.21--28 (2010).
Time ratio
Count of recursive call (== stack depth)
Fiber implementation
2017 (3) More lightweight switching
•Context exchange
•[copy] Thread states
•[ptr exchange] VM stack
•[ptr exchange] Machine stack
•“setcontext” calls sigprocmask
•Ruby threads/fibers use same signal mask
→ Useless system call
Fiber implementation
2017 (3) More lightweight switching
•Context exchange
•[copy->ptr exchange] Thread states
Before After
Thread
fib1
fib2
Store
Restore
Thread
fib1
fib2
ec1
ec2
ptr exchange
fib1
context fib2
context
fib1
context
fib2
context
Fiber implementation
2017 (3) More lightweight switching
•[Futurework] Use custom “setcontext” excludes
sigprocmask
•setcontext issues “sigprocmask” system call to restore
signal mask, but MRI doesn’t change signalmask so
that it is completely useless.
•This idea is also proposed at
https://rethinkdb.com/blog/making-coroutines-fast/
•License?
Fiber implementation
2017 (3) More lightweight switching
•Performance
2.15
2.2
2.25
2.3
2.35
2.4
Ruby 2.4.1 Modified
Sec
vm2_fiber_switch*
Fiber implementation
2017 (3) More lightweight switching
•Performance
2.36 2.25
0
1
2
3
Ruby 2.4.1 Modified
Sec
vm2_fiber_switch*
5%
improvement!
Fiber implementation
2017 (3) More lightweight switching
•Memory size / fiber
30% reduced!
2264
1616
0
500
1000
1500
2000
2500
Ruby 2.4.1 Modified
Bytes
sizeof(rb_fiber_t)
Fiber implementation
2017 (3) More lightweight switching
•Memory size / fiber
2,264 1,616
131,072 131,072
524,288 524,288
0
100,000
200,000
300,000
400,000
500,000
600,000
700,000
Ruby 2.4.1 Modified
Bytes
sizeof(rb_fiber_t) VM stack Machine stack
2017 (3) More lightweight switching
Not a valuable work?
•I spent this hack 2 or 3 months because of
code complicity.
•This work (hopefully) will be a basis of Guild
work (we need to pass context information
for each APIs like mrb_state on mruby)
Auto-Fiber proposal
Auto Fiber proposal
•“Fiber” enables writing scheduler by Ruby
programmer
•Maybe Seki-san introduce one example
•Why doesn’t an interpreter support it
natively? → Auto Fiber proposal
Auto Fiber proposal
https://bugs.ruby-lang.org/issues/13618
Auto Fiber proposal
Automatic schedule on I/O blocking
•Support Fiber scheduler
natively
• Don’t need to return
scheduler
•Switch Fibers on all blocking
I/O (and other ops)
• No need to change existing
programs
Comparison
Thread Fiber Auto Fiber
Suspend/contin
ue
Yes Yes Yes
Switch on timer Yes No No
Switch on I/O b. Yes No Yes
Synchronization Required Not required Required
Specify next No Yes No
Performance: Creation Heavy Lightweight Lightweight
Performance: Switch Lightweight Lightweight Lightweight
Advantage and Disadvantage
•Advantage
•Don’t need to modify existing programs
•Lightweight as a Fiber
•Safer than Threads (no preemption)
•Disadvantage
•Introduce “non-deterministic” dangers same as
Thread programs
• Non atomic operations can intercept accidentally.
Change the name…?
About this talk
•Behavior of Fiber
•History of Fiber
•Implementation of Fiber
•Auto Fiber proposal
Thank you for your attention
Koichi Sasada
<ko1@cookpad.com>

Weitere ähnliche Inhalte

Was ist angesagt?

Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
An introduction and future of Ruby coverage library
An introduction and future of Ruby coverage libraryAn introduction and future of Ruby coverage library
An introduction and future of Ruby coverage librarymametter
 
TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011bobmcwhirter
 
Fisl - Deployment
Fisl - DeploymentFisl - Deployment
Fisl - DeploymentFabio Akita
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
Gemification plan of Standard Library on Ruby
Gemification plan of Standard Library on RubyGemification plan of Standard Library on Ruby
Gemification plan of Standard Library on RubyHiroshi SHIBATA
 
The secret of programming language development and future
The secret of programming  language development and futureThe secret of programming  language development and future
The secret of programming language development and futureHiroshi SHIBATA
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)ngotogenome
 
TorqueBox for Rubyists
TorqueBox for RubyistsTorqueBox for Rubyists
TorqueBox for Rubyistsbobmcwhirter
 
How to distribute Ruby to the world
How to distribute Ruby to the worldHow to distribute Ruby to the world
How to distribute Ruby to the worldHiroshi SHIBATA
 
When Ruby Meets Java - The Power of Torquebox
When Ruby Meets Java - The Power of TorqueboxWhen Ruby Meets Java - The Power of Torquebox
When Ruby Meets Java - The Power of Torqueboxrockyjaiswal
 
The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018Charles Nutter
 
TorqueBox - Ultrapassando a fronteira entre Java e Ruby
TorqueBox - Ultrapassando a fronteira entre Java e RubyTorqueBox - Ultrapassando a fronteira entre Java e Ruby
TorqueBox - Ultrapassando a fronteira entre Java e RubyBruno Oliveira
 
2008 07-24 kwpm-threads_and_synchronization
2008 07-24 kwpm-threads_and_synchronization2008 07-24 kwpm-threads_and_synchronization
2008 07-24 kwpm-threads_and_synchronizationfangjiafu
 
TorqueBox - When Java meets Ruby
TorqueBox - When Java meets RubyTorqueBox - When Java meets Ruby
TorqueBox - When Java meets RubyBruno Oliveira
 
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)goccy
 

Was ist angesagt? (20)

Deployment de Rails
Deployment de RailsDeployment de Rails
Deployment de Rails
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
An introduction and future of Ruby coverage library
An introduction and future of Ruby coverage libraryAn introduction and future of Ruby coverage library
An introduction and future of Ruby coverage library
 
TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011
 
Fisl - Deployment
Fisl - DeploymentFisl - Deployment
Fisl - Deployment
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Gemification plan of Standard Library on Ruby
Gemification plan of Standard Library on RubyGemification plan of Standard Library on Ruby
Gemification plan of Standard Library on Ruby
 
The secret of programming language development and future
The secret of programming  language development and futureThe secret of programming  language development and future
The secret of programming language development and future
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
 
TorqueBox for Rubyists
TorqueBox for RubyistsTorqueBox for Rubyists
TorqueBox for Rubyists
 
How to distribute Ruby to the world
How to distribute Ruby to the worldHow to distribute Ruby to the world
How to distribute Ruby to the world
 
RubyGems 3 & 4
RubyGems 3 & 4RubyGems 3 & 4
RubyGems 3 & 4
 
When Ruby Meets Java - The Power of Torquebox
When Ruby Meets Java - The Power of TorqueboxWhen Ruby Meets Java - The Power of Torquebox
When Ruby Meets Java - The Power of Torquebox
 
近未来的並列 LL
近未来的並列 LL近未来的並列 LL
近未来的並列 LL
 
The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018
 
TorqueBox - Ultrapassando a fronteira entre Java e Ruby
TorqueBox - Ultrapassando a fronteira entre Java e RubyTorqueBox - Ultrapassando a fronteira entre Java e Ruby
TorqueBox - Ultrapassando a fronteira entre Java e Ruby
 
2008 07-24 kwpm-threads_and_synchronization
2008 07-24 kwpm-threads_and_synchronization2008 07-24 kwpm-threads_and_synchronization
2008 07-24 kwpm-threads_and_synchronization
 
Pfm technical-inside
Pfm technical-insidePfm technical-inside
Pfm technical-inside
 
TorqueBox - When Java meets Ruby
TorqueBox - When Java meets RubyTorqueBox - When Java meets Ruby
TorqueBox - When Java meets Ruby
 
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
 

Ähnlich wie Fiber in the 10th year

Ruby 1.9 Fibers
Ruby 1.9 FibersRuby 1.9 Fibers
Ruby 1.9 FibersKevin Ball
 
Ruby's Concurrency Management: Now and Future
Ruby's Concurrency Management: Now and FutureRuby's Concurrency Management: Now and Future
Ruby's Concurrency Management: Now and FutureKoichi Sasada
 
Multithread Your Application
Multithread Your ApplicationMultithread Your Application
Multithread Your ApplicationAndy Su
 
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009Harshal Hayatnagarkar
 
Concurrency: Rubies, Plural
Concurrency: Rubies, PluralConcurrency: Rubies, Plural
Concurrency: Rubies, PluralEleanor McHugh
 
Concurrency: Rubies, plural
Concurrency: Rubies, pluralConcurrency: Rubies, plural
Concurrency: Rubies, pluralehuard
 
“Purikura” culture in Japan and our web application architecture
“Purikura” culturein Japan andour web application architecture“Purikura” culturein Japan andour web application architecture
“Purikura” culture in Japan and our web application architectureKoichi Sakata
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraAllen Wirfs-Brock
 
Some Rough Fibrous Material
Some Rough Fibrous MaterialSome Rough Fibrous Material
Some Rough Fibrous MaterialMurray Steele
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9Ilya Grigorik
 
Van jaconson netchannels
Van jaconson netchannelsVan jaconson netchannels
Van jaconson netchannelsSusant Sahani
 
parallel-asynchronous-programming-java.pptx
parallel-asynchronous-programming-java.pptxparallel-asynchronous-programming-java.pptx
parallel-asynchronous-programming-java.pptx2022ac05156
 
Lightweight APIs in mRuby
Lightweight APIs in mRubyLightweight APIs in mRuby
Lightweight APIs in mRubyPivorak MeetUp
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysManuel Bernhardt
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
More Efficient Object Replication in OpenStack Summit Juno
More Efficient Object Replication in OpenStack Summit JunoMore Efficient Object Replication in OpenStack Summit Juno
More Efficient Object Replication in OpenStack Summit JunoKota Tsuyuzaki
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenixJared Smith
 

Ähnlich wie Fiber in the 10th year (20)

Ruby 1.9 Fibers
Ruby 1.9 FibersRuby 1.9 Fibers
Ruby 1.9 Fibers
 
Ruby's Concurrency Management: Now and Future
Ruby's Concurrency Management: Now and FutureRuby's Concurrency Management: Now and Future
Ruby's Concurrency Management: Now and Future
 
Multithread Your Application
Multithread Your ApplicationMultithread Your Application
Multithread Your Application
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
Fiber supervision in ZIO
Fiber supervision in ZIOFiber supervision in ZIO
Fiber supervision in ZIO
 
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009
 
Concurrency: Rubies, Plural
Concurrency: Rubies, PluralConcurrency: Rubies, Plural
Concurrency: Rubies, Plural
 
Concurrency: Rubies, plural
Concurrency: Rubies, pluralConcurrency: Rubies, plural
Concurrency: Rubies, plural
 
“Purikura” culture in Japan and our web application architecture
“Purikura” culturein Japan andour web application architecture“Purikura” culturein Japan andour web application architecture
“Purikura” culture in Japan and our web application architecture
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Some Rough Fibrous Material
Some Rough Fibrous MaterialSome Rough Fibrous Material
Some Rough Fibrous Material
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
 
Van jaconson netchannels
Van jaconson netchannelsVan jaconson netchannels
Van jaconson netchannels
 
parallel-asynchronous-programming-java.pptx
parallel-asynchronous-programming-java.pptxparallel-asynchronous-programming-java.pptx
parallel-asynchronous-programming-java.pptx
 
Lightweight APIs in mRuby
Lightweight APIs in mRubyLightweight APIs in mRuby
Lightweight APIs in mRuby
 
Reactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDaysReactive Web-Applications @ LambdaDays
Reactive Web-Applications @ LambdaDays
 
Scalax
ScalaxScalax
Scalax
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
More Efficient Object Replication in OpenStack Summit Juno
More Efficient Object Replication in OpenStack Summit JunoMore Efficient Object Replication in OpenStack Summit Juno
More Efficient Object Replication in OpenStack Summit Juno
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenix
 

Kürzlich hochgeladen

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, Adobeapidays
 
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 RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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 2024The Digital Insurer
 
"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 ...Zilliz
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
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 DevelopmentsTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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 Processorsdebabhi2
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
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 DiscoveryTrustArc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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...Martijn de Jong
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 

Kürzlich hochgeladen (20)

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
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
"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 ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Fiber in the 10th year

  • 1. Fiber in the 10th year Koichi Sasada ko1@cookpad.com
  • 2. About this talk •Behavior of Fiber •History of Fiber •Implementation of Fiber •Auto Fiber proposal
  • 3. Koichi Sasada http://atdot.net/~ko1/ •A programmer •2006-2012 Faculty •2012-2017 Heroku, Inc. •2017- Cookpad Inc. •Job: MRI development •Core parts •VM, Threads, GC, etc
  • 5. Fiber example Infinite generator fib = Fiber.new do Fiber.yield a = b = 1 loop{ a, b = b, a+b Fiber.yield a } end 10.times{ p fib.resume }
  • 6. Fiber example Infinite generator fib = Fiber.new do Fiber.yield a = b = 1 loop{ a, b = b, a+b Fiber.yield a } end 10.times{ p fib.resume } 1. Fiber creation 2. Resume Fiber 3. Return to the parent fiber 4. Resume fiber (again) 5. Return to the parent fiber 6. Resume fiber (again2)
  • 7. Fiber example Infinite generator fib = Fiber.new do Fiber.yield a = b = 1 loop{ a, b = b, a+b Fiber.yield a } end 10.times{ p fib.resume } 1. Fiber creation 2. Resume Fiber 3. Return to the parent fiber 4. Resume fiber (again) 5. Return to the parent fiber 6. Resume fiber (again2)
  • 8. Not a Proc? a = 0; b = 1 fib = Proc.new{ a, b = b, a+b a } p fib.call #=> 1 p fib.call #=> 1 p fib.call #=> 2 p fib.call #=> 3 p fib.call #=> 5 Proc can’t restart from the middle of block
  • 9. Proc (method) v.s. Fiber Proc (method) Fiber Start OK: call OK: Fiber#resume Parameters OK: block (method) parameters OK: block parameters Return OK: exit Proc/method OK: exit Proc/method Suspend NG: N/A OK: Fiber.yield Continue NG: N/A OK: Fiber#resume
  • 10. Fiber example Inner iterator to external iterator f1 = Fiber.new do 2.times{|i| Fiber.yield i} end p f1.resume #=> 0 p f1.resume #=> 1 p f1.resume #=> 2 # return value of #times p f1.resume #=> dead fiber called (FiberError)
  • 11. Fiber example Inner iterator to external iterator etc_passwd_ex_iter = Fiber.new do open('/etc/passwd').each_line{|line| Fiber.yield line } end p etc_passwd_ex_iter.resume #=> 1st line p etc_passwd_ex_iter.resume #=> 2nd line …
  • 12. Fiber example Inner iterator to external iterator # make Enumerator iter = open('/etc/passwd').each_line # Enumerator#next use Fiber implicitly p iter.next #=> 1st line p iter.next #=> 2nd line …
  • 13. Fiber example Agent simulation characters << Fiber.new{ loop{cat.move_up; Fiber.yield}} characters << Fiber.new{ loop{dog.move_left; Fiber.yield}} … loop{cs.each{|e| e.resume}; redraw}
  • 14. Fiber example Agent simulation characters << Fiber.new{ # you can specify complex rule for chars loop{ cow.move_up; Fiber.yield cow.move_right; Fiber.yield cow.move_down; Fiber.yield cow.move_left; Fiber.yield } }
  • 15. Fiber example Non-blocking IO scheduler Wait multiple IO ops with traditional “select” or modern “poll”, “epoll” interface
  • 16. Not a Thread? Thread Fiber Suspend/continue Yes Yes Switch on timer Yes No (explicit switch) Switch on I/O blocking Yes No (explicit switch) Synchronization Required Not required Specify next context No Yes Performance: Creation Heavy Lightweight Performance: Switch Lightweight Heavy (initial version) Lightweight (now)
  • 18. Fiber: Brief history •2007/05/23 cont.c (for callcc) •2007/05/25 Fiber impl. [ruby-dev:30827] •2007/05/28 Fiber introduced into cont.c •2007/08/25 Fix Fiber spec
  • 19. Background: Callcc and Fiber on Ruby 1.9 • 2007/01 YARV was merged without “callcc” • Biggest usage of “callcc” is for “Generator” • Convert an internal iterator to an external iterator • Usually one-shot continuation is required → Coroutine is enough for this purpose • Capturing continuation (callcc) is heavy operation • Implementation is easy because we can refer Ruby 1.8 user-level threads • 2007/05/?? I was introduced one paper something like generator for (maybe) C# (so I began to consider about this feature) • And I have a spare time at academic conference
  • 20. 2007/05/22 IRC log (seeing a blog post) 00:56:49 <ko1> うーむ,callcc 欲しいっすか English: Umm, do you want “callcc”?
  • 22. 2007/05/23 IRC log (nobu pointed out there are several bugs on callcc) 12:15:36 <ko1> callcc 禁止でいいよ EN: callcc should be prohibited 12:15:52 <ko1> これ作りながら,Fiber作ったほうが 速いなーとか思って亜 EN: Building callcc, I’m thinking that making Fiber is more straightforward.
  • 23. Fiber naming •The name “Fiber” is from Windows API • “A fiber is a unit of execution that must be manually scheduled by the application. Fibers run in the context of the threads that schedule them. Each thread can schedule multiple fibers. In general, fibers do not provide advantages over a well-designed multithreaded application. However, using fibers can make it easier to port applications that were designed to schedule their own threads.” https://msdn.microsoft.com/ja- jp/library/windows/desktop/ms682661(v=vs.85).aspx
  • 24. [ruby-dev:30828] Re: Supporting Fiber Naming of Fiber “Fiberでいいんじゃないでしょうか。 何かかっこいいですよね。” by shugo EN: “I’m ok the name of “Fiber”. Somewhat cool.” by shugo
  • 26. First Fiber is Coroutine Fiber#pass f1 = Fiber.new{ f2.pass; f2.pass} f2 = Fiber.new{ f3.pass} f3 = Fiber.new{ f1.pass} f1.pass No parents/children All routines are equivalent Co-operative routines = Coroutine NOTE: renamed to “Fiber#transfer” now
  • 27. Fiber#pass → Fiber#yield [ruby-dev:30847] Re: Supporting Fiber Matz’s idea
  • 28. Coroutine or Semi-coroutine •Coroutine is difficult • You need to manage all transitions of Fibers • Remember that most of languages have only “routine” (not “co-”) and it is easy to use. • Most of case, semi-coroutine is easy and enough • Exception handling • On semi-croutine, exceptions are raised to the parent Fiber(s) • Maybe it has critical BUG issue. •Coroutine is powerful • No limitation (a bit old-language constructs)
  • 29. [ruby-dev:31583] Fiber reviesed Semi-coroutine (Fiber) and Coroutine (Fiber::Core)
  • 30. 2007/08/25 IRC log 10:26:49 <ko1> 大クラス主義ならFiber に Semi も Coroutine も機能いっしょくたにするべきかなあ EN: Semi- and non-semi Coroutine may be in one class undr big class principle 10:32:15 <ko1> というわけで,いっしょくたにしてみる EN: So that I merged it. * It was just idea in two lines…
  • 31. Fiber::Core was removed Commit message does not work well…
  • 32. Final specification of Fiber • Semi-coroutine • Fiber#resume and Fiber.yield • Make parent and child relationship (tree) • Prohibit double resume • Coroutine • Fiber#transfer • Prohibt to call semi-coroutine methods on “transfer”ed fiber (coroutine) fib1 (parent) fib2 (child/parent) fib3 (child) resume resume double resume is prohibited NG!!
  • 34. Implementation history (1) 2007/05 Copy all machine stack (2) 2010/05 FIBER_USE_NATIVE (3) 2017/09 Switch only pointer
  • 35. Fiber context representation •Context: •Thread states (current program counter, etc) •VM stack •Machine stack •“Context switching” means exchange contexts
  • 36. Fiber implementation 2007 (1) Copy machine stack •Store and restore “Context” by copying machine stack machine stack area machine stack of fib1 machine stack of fib2 Store Restore Switch from running fib1 to suspended fib2
  • 37. Fiber implementation 2007 (1) Copy machine stack •Good •Same idea of a Ruby 1.8 user-level thread code •Not so many memory usage •Almost portable •Bad •Copy time is relative to stack-depth (O(N)) machine stack area machine stack of fib1 machine stack of fib2 Store Restore
  • 38. Fiber implementation 2010 (2) Use Native support •Switch machine stack by system APIs •Supported APIs •POSIX makecontext/setcontext •Win32 Fiber API •Machine stack exchange is only pointer exchange (O(1)) •Implemented by Mr. Shiba (with me)
  • 39. “A Fast Fiber Implementation for Ruby 1.9” “Ruby1.9での高速なFiberの実装”, 第51回プログラミング・シンポジウム予稿集, pp.21--28 (2010). Time ratio Count of recursive call (== stack depth)
  • 40. Fiber implementation 2017 (3) More lightweight switching •Context exchange •[copy] Thread states •[ptr exchange] VM stack •[ptr exchange] Machine stack •“setcontext” calls sigprocmask •Ruby threads/fibers use same signal mask → Useless system call
  • 41. Fiber implementation 2017 (3) More lightweight switching •Context exchange •[copy->ptr exchange] Thread states Before After Thread fib1 fib2 Store Restore Thread fib1 fib2 ec1 ec2 ptr exchange fib1 context fib2 context fib1 context fib2 context
  • 42. Fiber implementation 2017 (3) More lightweight switching •[Futurework] Use custom “setcontext” excludes sigprocmask •setcontext issues “sigprocmask” system call to restore signal mask, but MRI doesn’t change signalmask so that it is completely useless. •This idea is also proposed at https://rethinkdb.com/blog/making-coroutines-fast/ •License?
  • 43. Fiber implementation 2017 (3) More lightweight switching •Performance 2.15 2.2 2.25 2.3 2.35 2.4 Ruby 2.4.1 Modified Sec vm2_fiber_switch*
  • 44. Fiber implementation 2017 (3) More lightweight switching •Performance 2.36 2.25 0 1 2 3 Ruby 2.4.1 Modified Sec vm2_fiber_switch* 5% improvement!
  • 45. Fiber implementation 2017 (3) More lightweight switching •Memory size / fiber 30% reduced! 2264 1616 0 500 1000 1500 2000 2500 Ruby 2.4.1 Modified Bytes sizeof(rb_fiber_t)
  • 46. Fiber implementation 2017 (3) More lightweight switching •Memory size / fiber 2,264 1,616 131,072 131,072 524,288 524,288 0 100,000 200,000 300,000 400,000 500,000 600,000 700,000 Ruby 2.4.1 Modified Bytes sizeof(rb_fiber_t) VM stack Machine stack
  • 47. 2017 (3) More lightweight switching Not a valuable work? •I spent this hack 2 or 3 months because of code complicity. •This work (hopefully) will be a basis of Guild work (we need to pass context information for each APIs like mrb_state on mruby)
  • 49. Auto Fiber proposal •“Fiber” enables writing scheduler by Ruby programmer •Maybe Seki-san introduce one example •Why doesn’t an interpreter support it natively? → Auto Fiber proposal
  • 51. Auto Fiber proposal Automatic schedule on I/O blocking •Support Fiber scheduler natively • Don’t need to return scheduler •Switch Fibers on all blocking I/O (and other ops) • No need to change existing programs
  • 52. Comparison Thread Fiber Auto Fiber Suspend/contin ue Yes Yes Yes Switch on timer Yes No No Switch on I/O b. Yes No Yes Synchronization Required Not required Required Specify next No Yes No Performance: Creation Heavy Lightweight Lightweight Performance: Switch Lightweight Lightweight Lightweight
  • 53. Advantage and Disadvantage •Advantage •Don’t need to modify existing programs •Lightweight as a Fiber •Safer than Threads (no preemption) •Disadvantage •Introduce “non-deterministic” dangers same as Thread programs • Non atomic operations can intercept accidentally. Change the name…?
  • 54. About this talk •Behavior of Fiber •History of Fiber •Implementation of Fiber •Auto Fiber proposal
  • 55. Thank you for your attention Koichi Sasada <ko1@cookpad.com>