Share
Embed
Rubyにおける並行処理 / Concurrency in Ruby
イベント名:Money Forward Tech Day 2024
登壇日:2024年9月20日
登壇者:Edric(Pham Vuong Trieu)
説明:アプリケーションが複雑になり、より速く、より効率的な処理が求められる中で、並行処理の重要性が高まっています。Rubyの並行処理を利用することで、複数のタスクを同時に実行し、パフォーマンスと応答性を向上させることができます。このセッションでは、並行処理の基本概念を探り、Ruby に組み込まれた Thread や Fiber の仕組みについて掘り下げ、Parallel やAsync などの人気ライブラリの検証についてお話しします。
イベントURL:https://techday.moneyforward-dev.jp/2024/
Money Forward, Inc.
September 25, 2024
Transcript
59 slides
-
Pham Vuong Trieu (Edric) • 2021: マネーフォワードベトナムに入社 • 2021 -
◦ 現在: マネーフォワード クラウド会社設立 • 2021: Join Money Forward Vietnam • 2021 - ◦ Now: Money Forward Cloud Company Registration. -
目次 Table of contents 1. Concurrency Before Ruby 3 2.
Processes: Fast but Costly 3. Threads: GIL Issues 4. Ruby 3: Fiber & Scheduler 5. Ruby 3: Ractor 6. Choosing the Right Approach 1. Ruby 3以前の並行処理 2. プロセス: 速いがコストがかかる 3. スレッド: GILの問題 4. Ruby 3: Fiberとスケジューラ 5. Ruby 3: Ractor 6. 正しいアプローチの選択 -
Rubyの良いところ、悪いところ、そしてとても悪いところ The good, the bad and the ugly of Ruby
• The good: elegant syntax, fast to develop • The bad: performance and memory consumption • The ugly: concurrency model • 良い点: エレガントな構文、開発ス ピードの速さ • 悪い点: パフォーマンスとメモリ消費 • 厄介な点: 並行処理モデル -
なぜRubyは並行タスクの処理で評判が悪 かったのか? Why did Ruby have a bad reputation for
handling concurrency tasks? 質問 Question -
並列: 複数のタスクを同時に実行する Parallel: Executing multiple tasks at the same
time 並行処理と並列処理 Concurrency & Parallel -
バージョン3以前のRubyの並行処理について Ruby take on concurrency before version 3 • Concurrency
Options: Process and Thread • Challenges: ◦ Process: Expensive in terms of resources ◦ Thread: Limited by the Global Interpreter Lock (GIL) • 同時実行オプション : プロセスとスレッ ド • 課題: ◦ プロセス : リソースが高価になる ◦ スレッド : Global Interpreter Lock(GIL) による制限 -
プロセスの仕組み How processes work • Independent Execution: Processes run separately
and in parallel. • Child Process Details: Copies everything from the parent, including memory and Ruby interpreter. • Ruby Interpreter: Converts Ruby code into machine code, which can impact performance. • 独立実行 : プロセスは別々に並行して実行され る。 • 子プロセスの詳細 : メモリやRuby インタプリタ など、親プロセスからすべてをコピーする。 • Ruby インタプリタ : Ruby コードをマシンコード に変換、それがパフォーマンスに影響を与える ことがある。 -
シンプルなフィボナッチ関数による 「CPU バウンド」問題 Simple Fibonacci function for “CPU bound” problem CPUバウンド問題の例
Example for CPU bound problem -
• 並列計算のために複数のプロセスを 使う • IO.pipeによる出力の収集 • Using multiple processes
for parallel computing • IO.pipe to collect output プロセスのスピードアップ Speed up with process -
ベンチマーク Benchmark • Machine: Macbook pro M2 • CPU time:
• Normal run: ◦ CPU time: 3.28s ◦ Memory: 40 bytes • Process: ◦ CPU time: 1.67s ◦ Memory: 9032 bytes • マシン: マックブック Pro M2 • CPU時間: • 通常実行: ◦ CPU時間: 3.28s ◦ メモリ: 40バイト • プロセス: ◦ CPU時間: 1.67s ◦ メモリ: 9032バイト -
プロセス使用の悪い面 The bad side of using process • Child process
copies memory & Ruby interpreter => Waste resources • Cannot directly share data between process, have to use IO.pipe • IO.pipe only allow string data • 子プロセスがメモリをコピーすることと Rubyインタプリタ の組み合わせによ り、リソースが無駄になる。 • プロセス間で直接データを共有できな い。IO.pipe を使う必要がある。 • IO.pipeは文字列データ のみ許可す る。 -
• 直接使用する代わりにgem parallel を使用する • よりシンプルな実装で同じ速度 • Instead of
direct use, we can use gem parallel • Simpler implementation, same speed 代替手段: gem Parallelを使う Alternative: using gem Parallel -
• 軽量スレッド : スレッドはメモリを共有するため、 プロセスよりも効率的。 • Global Interpreter Lock
(GIL): 一度に1つの スレッドだけがRubyコードを実行できるようにす ることで、真の並列実行を制限する。 • Lightweight Threads: Threads share memory, making them more efficient than processes. • Global Interpreter Lock (GIL): Limits true parallel execution by allowing only one thread to execute Ruby code at a time. Rubyのスレッドの仕組み How Threads Work in Ruby -
• The Global Interpreter Lock (GIL)は、一度に 1つのネイティブ・スレッドしか Rubyコードを実行 できないようにする。
• Rubyは「グリーンスレッド」を使用し、スレッドの スケジューリングはOSが管理する。 • The Global Interpreter Lock (GIL) ensures that only one native thread can execute Ruby code at a time • Ruby uses "green threads," with thread scheduling managed by the OS The Global Interpreter Lock -
GILの長所と短所 Pros and cons of GIL • Pros: ◦ Simplifies
thread safety. ◦ Prevents deadlocks. • Cons: ◦ Limits true parallelism. ◦ Reduces performance in multi-core systems. • 長所: ◦ スレッドセーフの簡素化。 ◦ デッドロックの防止。 • 短所: ◦ 真の並列処理が制限される。 ◦ マルチコアシステムでのパフォーマンスを 低下させる。 -
• シナリオ : スレッドを使って複数のフィボナッチ数 の計算をする • 観察: 実行時間はシングルスレッドと変わらない •
結論: スレッドはCPUバウンドタスクのパフォー マンスを向上させない • Scenario: Calculating multiple Fibonacci numbers using threads • Observation: Runtime remains the same as a single-threaded approach • Conclusion: Threads do not improve performance for CPU-bound tasks CPUバウンド問題にスレッドを使う Using Threads for CPU-Bound Problems -
スレッドの強み Strengths of Threads • Ideal for I/O-Bound Tasks: ◦
API Requests: Efficiently handle network communication. ◦ File Operations: Manage reading and writing to disk effectively. • I/Oバウンドタスクに最適 ◦ APIリクエスト: ネットワーク通信を効率的 に処理。 ◦ ファイル操作: ディスクの読み込み・書き 込みを効率的に管理する。 -
例: 複数のウェブページのフェッチ 課題: ブロッキングせずに複数のI/O操作を効 率的に処理する Example: Fetching multiple
web pages Challenge: Handling multiple I/O operations efficiently without blocking I/Oバウンドタスクにスレッドを活用する Leveraging Threads for I/O-Bound Tasks -
パフォーマンス向上 : マルチスレッドで3倍高 速化 メモリ使用量: シングルスレッド実行とほぼ同 じ Performance Improvement:
3 times faster with multi-threading Memory Usage: Nearly the same as single-threaded execution ベンチマーク Benchmark -
Ruby Fiber入門 Introduction to Ruby Fiber • Introduced in Ruby
1.9 • Initially overlooked until the enhancements in Ruby 3 • Fiber is Ruby's implementation of coroutines, providing a way to pause and resume code execution within a single thread. • Ruby 1.9で登場。 • Ruby 3で強化されるまで見過ごされ ていた。 • FiberはRubyのコルーチン実装であ り、単一スレッド内でコード実行を一時 停止したり再開したりする方法を提供 する。 -
コルーチンとは何か? What is a Coroutine? • A coroutine is a
general control structure whereby flow control is cooperatively passed between two different routines without returning. • Unlike threads, coroutines yield control explicitly, allowing for more predictable concurrency. • コルーチンは、フロー制御が戻ること なく2つの異なるルーチン間で協力的 に渡される一般的な制御構造である。 • スレッドとは異なり、コルーチンは明示 的に制御を譲渡する ため、より予測 可能な並行処理を可能にする。 -
各Fiberは何らかのアクションを実行し、 Fiber.yieldを使って一時停止し、制御が戻 されると再開する。 Each fiber performs some action, pauses using
Fiber.yield, and then resumes when control is passed back to it. 例: セットアップ Example: setup -
Fiberは制御の譲渡と再開を繰り返し、協 調的マルチタスクの管理に使用できること を示している。 The fibers yield and resume control back
and forth, demonstrating how fibers can be used to manage cooperative multitasking. 例:Fiberの実行 Example: Fiber Execution -
Ruby 3による進化 Evolution with Ruby 3 • Fiber Scheduler: Introduced
in Ruby 3 as an interface for implementing cooperative multitasking. • Purpose: To enable non-blocking I/O operations by integrating Fibers with event-driven programming. • Fiber Scheduler: 協調型マルチタス クを実装するためのインタフェース と してRuby 3で登場。 • 目的: イベント駆動型プログラミングに Fiberを統合することで、ノンブロッキ ング I/O 操作を可能にする。 -
非同期ジェムの紹介 Introduction to the Async Gem • Async is a
Ruby gem that simplifies the creation and management of concurrent tasks using Fibers. • Key Features: ◦ Event-driven concurrency. ◦ Non-blocking I/O. ◦ Easy integration with Fiber Scheduler. • Asyncは、Fibersを使った並行タスク の作成と管理を簡素化するRuby gemです。 • 主な特徴: ◦ イベント駆動型並行処理。 ◦ ノンブロッキングI/O。 ◦ Fiber Schedulerとの統合しやすさ。 -
Asyncの仕組み How does Async work? • The Async gem includes
an event loop that monitors various I/O operations • When an operation is ready (e.g., data is available to read, or a timer has expired), the event loop resumes the corresponding Fiber to continue its execution • Async gem には、さまざまな I/O 操 作を監視するイベントループ が含ま れています。 • 操作の準備が整うと(例えば、データ が読み込めるようになったり、タイマー が切れたり)、イベントループは対応 するFiberを再開し、その実行を継続 します。 -
非同期オペレーションを簡素化し、I/Oバウ ンドタスクのパフォーマンスを向上 Simplifies asynchronous operations and improves performance for I/O-bound
tasks Asyncを使ってAPIをフェッチする Using Async to fetch API -
Ractor 入門 Introduction to Ractor • What is Ractor? ◦
A new concurrency abstraction introduced in Ruby 3. ◦ Designed to provide true parallelism for CPU-bound tasks. • Objective: ◦ Enable parallel execution of code in a way that avoids the Global Interpreter Lock (GIL). • Ractorとは? ◦ Ruby 3で導入された新しい並行処理の抽 象化手法。 ◦ CPUバウンドタスクで真の並列性を実現 できるように設計されている。 • 目的: ◦ the Global Interpreter Lock(GIL)を回 避しつつコードの並列実行を可能にする。 -
• 並列実行 : Ractorは互いに独立して同時に実行さ れます。 • 分離: Ractorは互いに分離されており、共有メモリ やデータ競合の問題は発生しません。
• 通信: Ractorはスレッドセーフなメッセージパッシン グで通信します。 • Parallel Execution: Ractors run concurrently and independently of each other. • Isolation: Ractors are isolated from each other, ensuring no shared memory or data race issues. • Communication: Ractors communicate via message passing, which is thread-safe. Ractorのキーコンセプト Key Concepts of Ractor -
Ractor 対 スレッド Ractor vs. Thread • Parallelism: Ractors provide
true parallelism (unlike Threads that are limited by the GIL). • Isolation: Ractors do not share state or memory, reducing risks of data corruption. • Use Cases: Ractors are ideal for CPU-bound tasks needing parallel execution. • 並列性: Ractorは真の並列性が実現 される(GILによって制限されるスレッ ドとは異なる)。 • 分離: Ractorは状態やメモリーを共 有しないため、データ破損のリスクが 低減する。 • 使用例: Ractorは並列実行が必要な CPUバウンドタスクに最適。 -
Ractorは真の並列性を実現し、複数の CPUコアを活用するために実行を分離する Ractors provide true parallelism and isolate execution
to leverage multiple CPU cores CPUバウンドタスクのためにRactorを活用 Leveraging Ractor for CPU-Bound Tasks -
プロセス Process What it’s for: Heavy, isolated tasks that need
full parallelism across multiple CPU cores. Example Use Case: Running separate, independent services or handling tasks that require strong memory isolation. Key Method: Process.fork, Process.wait 用途: 複数のCPUコアにまたがり、完全な 並列処理が必要な、重く、分離されたタス ク。 使用例: 個別の独立したサービスの実行 や、強力なメモリ分離を必要とするタスクの 処理。 主なメソッド : Process.fork、 Process.wait -
スレッド Thread What it’s for: Tasks that can run concurrently
within the same memory space, especially I/O-bound tasks. Example Use Case: Performing multiple I/O operations like reading files or making API requests simultaneously. Key Method: Thread.new, Thread.join 用途: 同じメモリ空間内で並行して処理で きるタスク、特にI/Oバウンドタスク。 使用例: ファイルの読み取りやAPIリクエス トのように、複数のI/O操作を同時に実行 する。 主なメソッド : Thread.new、Thread.join -
Fiber What it’s for: Lightweight, cooperative multitasking within a single
thread, great for non-blocking I/O. Example Use Case: Handling multiple network connections in a web server without blocking. Key Method: Fiber.new, Fiber.yield 用途: シングルスレッド内での軽量で協調 的なマルチタスク、ノンブロッキングI/Oに 最適。 使用例: Webサーバーで複数のネットワー ク接続をブロッキングせずに処理する。 主なメソッド : Fiber.new、Fiber.yield -
Ractor What it’s for: True parallelism with isolated memory, ideal
for tasks that benefit from concurrent execution without sharing state. Example Use Case: Parallel data processing or computations that require isolation between concurrent tasks. Key Method: Ractor.new, Ractor.take 用途: 分離メモリによる真の並列性の実 現。ステートを共有することなく並行実行が 可能なタスクに最適。 使用例: 並行タスク間の分離が必要な並 列データ処理や計算。 主なメソッド : Ractor.new、Ractor.take -
• 日英併記 ◦ 記載方法はテンプレに従ってくださ い ◦ 日本語話者の方は英語訳もご自身 で記載をお願いします。その後、 TechDayの翻訳チームがレビュー します
• デモ動画 ◦ 機材オペレーションの関係で、今回 は当日のデモななしで動画でお願い します ◦ 動画の共有方法は検討中のため、 確定したら再度アナウンスします スライド レギュレーション 1 / Slide Regulation 1 • Write in both Japanese and English ◦ Please follow the writing template ◦ You only need to write the English. The translation team will then translate it into Japanese. • Demonstration video ◦ Due to equipment operation, please use video instead of a demo on the day of the event. ◦ The method of sharing the video is still under consideration and will be announced again when it is finalised. -
• 文字サイズ ◦ 本文 : 最小18 pt ◦ 注釈 : 最小14 pt ◦ 見出し: 最小22
pt スライド レギュレーション 2 / Slide Regulation 2 • Font size ◦ Main Text: min 18 pt ◦ Annotation: min14 pt ◦ Title: min 22 pt -
スライドをコピー Copy the slide テンプレートの使用方法 / How to use the
template [レイアウト▼]から 対象のデザインを選択 Select design from Apply layout. 新規スライドを追加 Add a new slide 01 02 03 ※こちらのスライドはマスターデータのため、 コピーしてご利用ください * Please copy and use these slides as master data. -
• Career JP/EN • SNSアカウント / SNS Account 名前やニックネーム name
or nickname この範囲には文字がはみ出さないようにしましょう(このオレンジのオブジェクトは公開時には削除してください) No text should extend beyond this area! This orange object should be deleted when published. -
まとめや話の切り替え Summarising and switching between stories この範囲には文字がはみ出さないようにしましょう(このオレンジのオブジェクトは公開時には削除してください) No text should
extend beyond this area! This orange object should be deleted when published. -
JP コード紹介テキストコード紹介テキストコード紹介テキスト EN Code Introduction Text Code Introduction Text Code
この範囲には文字がはみ出さないようにしましょう(このオレンジのオブジェクトは公開時には削除してください) No text should extend beyond this area! This orange object should be deleted when published. -
JP コード紹介テキストEN Code Introduction JP コード紹介テキストコード紹介テキ ストコード紹介テキスト EN Code Introduction
Text Code Introduction Text Code この範囲には文字がはみ出さないようにしましょう(このオレンジのオブジェクトは公開時には削除してください) No text should extend beyond this area! This orange object should be deleted when published. -
JP テキスト • JPタイトル EN Title この範囲には文字がはみ出さないようにしましょう(このオレンジのオブジェクトは公開時には削除してください) No text
should extend beyond this area! This orange object should be deleted when published. EN Text • -
JP テキスト EN Text JPタイトル EN Title この範囲には文字がはみ出さないようにしましょう(このオレンジのオブジェクトは公開時には削除してください) No
text should extend beyond this area! This orange object should be deleted when published. -
EN (Sample)Money Forward is developing numerous services across eight locations,
both domestic and international, including development bases in Vietnam and India. JP (例)マネーフォワードはベトナムやインド の開発拠点を含む国内外8拠点で多数の サービスを開発しています この範囲には文字がはみ出さないようにしましょう(このオレンジのオブジェクトは公開時には削除してください) No text should extend beyond this area! This orange object should be deleted when published.