Wojciech Mazur's presentation on "Implementing multithreading in Scala Native" as featured at the 2024 Scalar conference in Warsaw.
Size: 8.41 MB
Language: en
Added: Jun 17, 2024
Slides: 28 pages
Slide Content
Wojciech Mazur Implementing multithreading in Scala Native …or a story of 201 little pains
AboutMe.md Scala 3 Compiler Team at VirtusLab Lead of Scala Native team Open Community Build, Scala 3 migrations, Scala 3 compiler (spuriously)
Goals for SN multithreading Java Threads API Mostly-compliant JVM semantics Easy cross-compilation between JVM scala.concurrent*. , scala.collection.concurrent.* java.util.concurrent.*
Timeline August 2021 - First multithreading commits December 2021 - E nd of Scala Native founding September 2022 - Founding restored, multithreading work starts March 2023 - To be released soon, just a few more improvements March 2024 - Scala Native 0.5.0
Scala Native 0.5.0 Multithreading support (duh!) Initial 32-bit architecture support Initial source level debugging support SIP-51 (unfreezing Scala 2 standard library) ready Java Service Providers Interface - explicitly configured Continuations primitives - virtual threads to be added later
Scala Native 0.5.0 250+ PRs 120 000+ added lines of code 40 000+ modified lines of code 16 contributors
Stop the world T1 T2 T4 T3 T5 Some thread triggered GC. Start Stop-The-World event All threads stopped Execute GC. Resume threads
Safe points
How to stop the threads? Suspending Threads Cooperative Interruptible Suspend by sending signal to thread Blocking calls can fail: Requires recovery in user code Boehm GC Check if GC wants to stop threads Yields only in safe code locations Polling for stop event injected to user code JVM, .Net and Scala Native Immix
Yield points May trigger segmentation fault!
What if GC want’s to collect?
…or treat all external calls as potentially blocking By default inform GC only about potentially blocking calls
Where to keep synchronization state? Embed in object Map[Object, ObjectMonitor] Don’t synchronize? slow, does not permit object GC JVM compliance broken Increased memory usage
Keeping state of object monitors? Most objects do not experience enter monitor concurrently Allocating monitor on first enter to object monitor is wasting memory
Initially monitor= NULL (thin, unlocked) Lock/unlock using CompareAndSwap If CAS fails or using wait - inflate Operate on bit set How object monitors work? Created by inflation of thin lock Lock/unlock using CompareAndSwap Access based on queue ordering or data race Can notify waiting threads Can nominate successor thread Operate on structure assigned to object Thin locks Fat locks