Article

Thread Leaks

Detects when threads aren’t closed after use.

Overview

This check detects threads created with the pthread_create(_:_:_:_:) function without a corresponding call to the pthread_join(_:_:) function. Leaked threads can result in decreased performance and crashing of your program.

Leaked Thread in C

In the following example, the thread variable is created but not closed after use.

void *run(){
    pthread_exit(0);
}
pthread_t thread;
pthread_create(&thread, NULL, run, NULL); // Error: thread leak
sleep(1);

Solution

Add a call to the pthread_join(_:_:) function.

void *run(){
    pthread_exit(0);
}
pthread_t thread;
pthread_create(&thread, NULL, run, NULL);
sleep(1);
pthread_join(thread, NULL); // Correct

Alternatively, you can create a detached thread by passing the PTHREAD_CREATE_DETACHED attribute to pthread_create(_:_:_:_:), or calling pthread_detach(_:) on the thread after creation.

See Also

Thread Sanitizer Checks

Data Races

Detects unsynchronized access to mutable state across multiple threads.

Swift Access Races

Detects when multiple threads call a mutating method on the same structure, or pass a shared variable as inout without synchronization.

Races on Collections and Other APIs

Detects when a thread accesses a mutable object while another thread writes to that object, causing a data race.

Uninitialized Mutexes

Detects when a mutex is used before it’s initialized.