WWDC 2016 Thread Sanitizer and s
Thread Sanitizer(TSan)
Use of uninitialized mutexes
Thread leaks (missing pthread_join
)
Unsafe calls in signal handlers(ex:malloc
)
Unlock from wrong thread
In Xcode
- Edit Scheme - Diagnostics tab
- "Enable Thread Sanitizer" checkbox
- Build and Run
- View all of the generated runtime issues
- Can choose to break on every issue
Data Race
Multiple threads access the same memory without synchronization
At least one access is a write
May end up with any value or even memory corruption!
Reasons for Data Races
Can indicate a problem with the structure of your program
Often means that synchronization is missing
建议使用同步队列来保证数据竞争的发生
Choosing the Right Synchronization API
- Use GCD
Dispatch racy accesses to the same serial aueue - Use pthread API,NSLock
pthread_mutex_lock()
to synchronize accesses - New os_unfair_lock(use instead of OSSpinLock)
- Atomic operations
More in WWDC
Concurrent Programming With GCD in Swift 3
没有办法捕获到所有的数据竞争和其他情况,因为有上限,会根据规律或者随机替换原有的线程操作(超过四个有可能会失效?)
Detecting a Race
Every thread stores (in thread local):
Thread's own timestamp
The timestamps for other thread that establish the points of synchronization
Timestamps are incremented on every memory access
Compiler Instruments memory Accesses
For every access:
Records the information about the access
Checks if that access participates in a race
Thread Sanitizer
Timing does not matter
Can detect races even if they did not manifest during the particular run
The more run time coverage the better
Run all your tests with TSan!
Find Bugs Without Running Code
Does not require running code (unlike sanitizers)
Great at catching hard to reproduce edge-case bugs
Supported only for C,C++,and Object-C
Analysis
Clang Static Analyzer in Xcode
- Product > Analyze or
Product > Analyze "SingleFile.m" - View in Issue Navigator
-
Explore Issue Path
image.png