File: mutex_cycle_long.c

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (42 lines) | stat: -rw-r--r-- 1,147 bytes parent folder | download | duplicates (38)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// RUN: %clangxx_tsan %s -o %t
// RUN: not %run %t 5 2>&1 | FileCheck %s
// RUN: not %run %t 10 2>&1 | FileCheck %s
// RUN: not %run %t 15 2>&1 | FileCheck %s
// RUN: not %run %t 20 2>&1 | FileCheck %s
// RUN: %run %t 30 2>&1 | FileCheck %s --check-prefix=CHECK-TOO-LONG-CYCLE

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  int num_mutexes = 5;
  if (argc > 1) num_mutexes = atoi(argv[1]);

  pthread_mutex_t m[num_mutexes];
  for (int i = 0; i < num_mutexes; ++i)
    pthread_mutex_init(&m[i], NULL);
  
  for (int i = 0; i < num_mutexes - 1; ++i) {
    pthread_mutex_lock(&m[i]);
    pthread_mutex_lock(&m[i + 1]);

    pthread_mutex_unlock(&m[i]);
    pthread_mutex_unlock(&m[i + 1]);
  }

  pthread_mutex_lock(&m[num_mutexes - 1]);
  pthread_mutex_lock(&m[0]);

  pthread_mutex_unlock(&m[num_mutexes - 1]);
  pthread_mutex_unlock(&m[0]);

  for (int i = 0; i < num_mutexes; ++i)
    pthread_mutex_destroy(&m[i]);

  fprintf(stderr, "PASS\n");
}

// CHECK: ThreadSanitizer: lock-order-inversion (potential deadlock)
// CHECK-TOO-LONG-CYCLE: WARNING: too long mutex cycle found
// CHECK: PASS