Thread Sanitizer — also known as TSan, is a debugging tool that detects race conditions, between threads.
// Sanitizer: “Removing bugs from hands” 😛
Curious to know more, let’s dive in
Concepts that should be understood before using Thread Sanitizer.
What is a thread?
A thread is sequence of instructions that can be executed by a runtime.
Lets say, in an application you might have one write thread, that would perform write operation, and another would be read thread, that would perform the read operation.
Threads are especially useful when you need to perform a lengthy task, but don’t want it to block the execution of the rest of the application, so you divide the whole code into separate threads, that would be doing separate tasks.
Each application in OS X or iOS is made up of one or more threads, each of which represents a single path of execution through the application’s code.
Every application starts with a single thread, which runs the application’s main function.
What is the data race condition?
Data race, is actually a part of Concurreny Problems.
As we all know how critical is to keep track of all the accesses to a shared variable, in a way that no two threads would be able to access the same shared variable at the same time.
Basically, data race is nothing but accessing the same shared address from different threads at the same time.
Lets’ understand with small e.g
Shared resource or variable : Account_Balance
And the two threads are:
Thread 1 -> will update the account balance, so that would be a write thread
Thread 2-> will read the account balance, so that would be a read thread.
So if Thread 1 and Thread 2 would try to access, or modify the Account_Balance variable, at the same time, without synchronization, this would leads to Data race.
So in general data race is
- 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!
What is the impact of race conditions?
So if two threads will try to access the same address, then we would end up with below stated problems.
- Unpredictable behavior
- Memory corruption
- Flaky tests: Tests that return both passes and failures despite no changes to the code or the test itself.
- Weird crashes
Understood a few concepts, 100% awesome…. But …. curious to know more like…..
What is the use of Thread Sanitizer?
Ans :
The Thread Sanitizer, commonly referred to as TSan, is a tool Apple provides as part of the LLVM compiler.
TSan allows you to identify when multiple threads attempt to access the same memory without providing proper access synchronization.
We usually enable this as we know we are working in a multi threaded environment, and we would be having Data race and other weird cases.
How we can enable TSan, to detect these conditions in a multi-threaded environment?
Ans:Note: TSan is only supported when running on the simulator.
Thread Sanitizer (TSan) in Xcode
- Edit Scheme- Run — Diagnostics tab
- “Enable Thread Sanitizer” checkbox
- Build and Run
- View all of the generated runtime issues
Note: TSan is only supported when running on the simulator.
Awesome, let’s learn more…..
What all problems we can debug using this Tool?
Ans:
- Data races
- Swift access races
- Races on collections and other APIs
- Uninitialized mutexes
- Thread leaks
Before diving into this, just wanted to nudge that
Using Actors we can solve data races
The Concurrency Framework announced at WWDC 2021 introduced Actors for synchronizing access to data. This is the best solution for solving data access-related bugs and should be more straightforward than dispatch queues.
To show the concept of how TSan detects each issues , and to know exactly where we have to fix the issue, we used dispatch queues to fix the problem
Let’s start
1) Data races
Detects unsynchronized access to mutable state across multiple threads.
How data race occurs?
Get Unleased_Coder’s stories in your inbox
Join Medium for free to get updates from this writer.
// We create a lazy testVariable, and check below how two thread access the same lazy var, and ends up in a data race issue.
Enable the TSan tool from the edit schema, now run again you will see the error, as shown below
Check the terminal, it says data race issues with the getter.
Let’s fix this
// We can fix this by creating a lockQueue using DispatchQueue
// Using a lock queue, we synchronized access and ensured that only one thread at a time accessed the testVariable variable
Data race… I know how to debug inside a large code base.
Yoii… Let’s learn about more issue
2) Swift access races
Detects unsynchronized access to mutable state across multiple threads in Swift.
How swift access races occur?
// We create a variable access_Issue_Var
// Check below how one thread does the write access, and another does the read access at the same time and ends up in a swift access race.
When we run the code, Tsan will report the issue, as shown below
Check the terminal, it says Swift access race issues with the getter.
Let’s fix this
// We can fix this by creating a lockQueue using DispatchQueue
// Using a lock queue, we synchronized access and ensured that only one thread at a time accessed can either do a read or a write operation.
3) Races on collections and other APIs
Detects when one thread accesses a mutable object while another thread is writing to it.
// This is more related to when we are working with Array, Dict, or any collection types
How do Races on collections and other APIs occur?
// We create an array collection variable, named as array inside the function
// Check below how the one thread enumerates a mutable array, and another does the write access at the same time and ends up in a swift access race on collections.
When we run the code, Tsan will report the issue, as shown below
Check the terminal, it says Swift access race on collection.
Let’s fix this
// We can fix this by creating a lockQueue using DispatchQueue
// Using a lock queue, we synchronized access and ensured that only one thread at a time accessed can either do a read or a write operation.
4) Uninitialized mutexes
Detects when you use an uninitialized mutex.
What does Tsan detect in this case?
// When we use any c libraries inside the swift code, and declare an uninitialized mutex variable,
// Tsan reports the issue that mutex is uninitialized.
static pthread_mutex_t mutex; // declare an uninitialized mutex variablevoid performWork() {
pthread_mutex_lock(&mutex); // Error: uninitialized mutex
// ...
pthread_mutex_unlock(&mutex);
}Let’s fix this
Use the pthread_once(_:_:) function to initialize a mutex before you use it, check below
// To Fix we created a once var
static pthread_once_t once = PTHREAD_ONCE_INIT;static pthread_mutex_t mutex;// Initialize the mutext before use
void init() {
pthread_mutex_init(&mutex, NULL);
}// Fixed by using pthread_once
void performWork() {
pthread_once(&once, init); // Correct
pthread_mutex_lock(&mutex);
// ...
pthread_mutex_unlock(&mutex);
}
5) Thread leaks
Detects when you don’t close threads after use.
What does Tsan detect in this case?
// Lets creates a thread variable, but doesn’t close it after use:
// Tsan reports the issue that we have a thread leak, as shown below .
void *run(){
pthread_exit(0);
}
pthread_t thread;
pthread_create(&thread, NULL, run, NULL); // Error: thread leak
sleep(1);Let’s fix this
Add a call to the pthread_join(_:_:) function.
void *run(){
pthread_exit(0);
}
pthread_t thread;
pthread_create(&thread, NULL, run, NULL);
sleep(1);// Fix this issue by calling pthread_join
pthread_join(thread, NULL); // CorrectAwesome :)…… Now, I know all the issues that I can debug using Tsan,
Do we have anything else to learn, about TSan?
Yup little more left,
Let’s understand a little about TSan Build Flow, and how it actually works
TSan Build Flow
In order to use Thread Sanitizer, Xcode passes a special flags to both Clang and Swift compilers that instruct them to produce an instrumented binary. Below are the flags
-fsanitize=thread(clang)-santize=thread(swiftc)-enableThreadSanitizer YES(xcodebuild)
// This binary links to a TSan runtime library that is used by the instrumentation to both monitor the execution of the program and detect those threading issues.
The compiler will add “flags” around each memory access to check whether certain access participates in a race
func check_On_Two_Thread() {
// Thread 1, Background Thread
DispatchQueue.global().async {
// Compiler adds a flag here, and keeps the eye
// on the access participants, that leads to race
print(self.testVariable)
}
// Thread 2, Main Thread
// Compiler will add flag here
print(self.testVariable)
}There are restrictions on the Thread Sanitizer
You can’t use Thread Sanitizer to diagnose iOS, tvOS, and watchOS apps running on a device.
Use Thread Sanitizer only on your 64-bit macOS app, or to diagnose your 64-bit iOS, tvOS, or watchOS app running in Simulator.
What is the PERFORMANCE IMPACT?
Because Thread Sanitizer inserts diagnostics into your code, it increases memory usage by five to ten times. Running your code with these diagnostics also introduces a 2x to 20x slowdown of your app.
To improve your code’s memory usage, compile your code with the
-O1optimization.
Yup, we are done.
That’s all, hope you liked it. Hopefully, you can catch bugs and fix some crashes that have been in your code for a long time.
To inspire me, to write more articles like this, kindly follow me
Kindly feel free to leave a comment or question. I will be really happy in receiving your feedback.
Have You Found It Useful? Comment IT









