Skip to content

Instantly share code, notes, and snippets.

@spetrunia
Created December 21, 2020 10:13
Show Gist options
  • Save spetrunia/77274cf2d5848e0a7e090d622695ed4e to your computer and use it in GitHub Desktop.
Save spetrunia/77274cf2d5848e0a7e090d622695ed4e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <pthread.h>
struct ST {
pthread_mutex_t mutex;
char *name;
};
int main(int argc, char **argv) {
ST locks[3];
for (int i=0; i < 3; ++i) {
pthread_mutex_init(&locks[i].mutex, NULL);
}
printf("Init done\n");
// Step 1
pthread_mutex_lock(&locks[0].mutex);
pthread_mutex_lock(&locks[1].mutex);
pthread_mutex_unlock(&locks[0].mutex);
pthread_mutex_unlock(&locks[1].mutex);
printf("Step 1 done\n");
// Step 2
pthread_mutex_lock(&locks[1].mutex);
pthread_mutex_lock(&locks[0].mutex);
pthread_mutex_unlock(&locks[1].mutex);
pthread_mutex_unlock(&locks[0].mutex);
printf("Step 2 done\n");
for (int i=0; i < 3; ++i) {
pthread_mutex_destroy(&locks[i].mutex);
}
return 0;
}
@spetrunia
Copy link
Author

Init done
Step 1 done
==================
WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock) (pid=8657)
  Cycle in lock order graph: M6 (0x7ffead0d55d0) => M7 (0x7ffead0d5600) => M6

  Mutex M7 acquired here while holding mutex M6 in main thread:
    #0 pthread_mutex_lock <null> (a.out+0x441816)
    #1 main <null> (a.out+0x4b398d)

    Hint: use TSAN_OPTIONS=second_deadlock_stack=1 to get more informative warning message

  Mutex M6 acquired here while holding mutex M7 in main thread:
    #0 pthread_mutex_lock <null> (a.out+0x441816)
    #1 main <null> (a.out+0x4b39f9)

SUMMARY: ThreadSanitizer: lock-order-inversion (potential deadlock) (/home/psergey/a.out+0x441816) in pthread_mutex_lock
==================
Step 2 done
ThreadSanitizer: reported 1 warnings

@spetrunia
Copy link
Author

Compilation step:

clang++-10 -fsanitize=thread test-asan.cc 
./a.out

Copy link

ghost commented Dec 27, 2020

Looks like this is a known issue in tsan: google/sanitizers#814

Copy link

ghost commented Dec 27, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment