Section 10/161 menit
10. Thread Sanitizer & Runtime Detection
10. Thread Sanitizer & Runtime Detection
Meskipun Swift 6 mendeteksi data race di compile time, Thread Sanitizer (TSan) tetap berguna untuk:
- Mendeteksi race di kode
@unchecked Sendable - Mendeteksi race yang melalui C/ObjC boundary
- Validasi kode concurrent selama migration ke Swift 6
Mengaktifkan TSan
swift
# Via command line
swift test --sanitize=thread
# Di Xcode: Product > Scheme > Edit Scheme > Run > Diagnostics > Thread Sanitizer
Membaca TSan Report
swift
WARNING: ThreadSanitizer: data race (pid=12345)
Write of size 8 at 0x... by thread T2:
#0 UserCache.store(user:forKey:) UserCache.swift:15
#1 ...
Previous read of size 8 at 0x... by main thread:
#0 UserCache.user(forKey:) UserCache.swift:19
#1 ...
SUMMARY: ThreadSanitizer: data race UserCache.swift:15
Interpretasi:
- Thread T2 melakukan write ke alamat memori tertentu di baris 15
- Main thread melakukan read dari alamat yang sama di baris 19
- Keduanya terjadi tanpa synchronization → data race
TSan Suppression untuk False Positives
swift
// Jika TSan melaporkan false positive untuk @unchecked Sendable
// yang sudah benar-benar thread-safe
// File: tsan_suppressions.txt
// race:ThreadSafeQueue::enqueue
// race:ThreadSafeQueue::dequeue
// Aktifkan suppression file
// TSAN_OPTIONS="suppressions=tsan_suppressions.txt" swift test --sanitize=thread