File: signal_in_mutex_lock.cpp

package info (click to toggle)
llvm-toolchain-20 1%3A20.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 2,111,696 kB
  • sloc: cpp: 7,438,781; ansic: 1,393,871; asm: 1,012,926; python: 241,771; f90: 86,635; objc: 75,411; lisp: 42,144; pascal: 17,286; sh: 8,596; ml: 5,082; perl: 4,730; makefile: 3,591; awk: 3,523; javascript: 2,251; xml: 892; fortran: 672
file content (79 lines) | stat: -rw-r--r-- 2,064 bytes parent folder | download | duplicates (15)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// RUN: %clang_tsan %s -lstdc++ -o %t && %run %t 2>&1 | FileCheck %s

#include "test.h"
#include <pthread.h>
#include <signal.h>
#include <stdio.h>

#include <atomic>
#include <cassert>
#include <condition_variable>
#include <mutex>

std::mutex sampler_mutex; //dummy mutex to lock in the thread we spawn.
std::mutex done_mutex;    // guards the cv and done variables.
std::condition_variable cv;
bool done = false;
std::atomic<bool> spin = true;

void *ThreadFunc(void *x) {
  while (spin) {
    // Lock the mutex
    std::lock_guard<std::mutex> guard(sampler_mutex);
    // Mutex is released at the end
  }

  return nullptr;
}

static void SigprofHandler(int signal, siginfo_t *info, void *context) {
  // Assuming we did some work, change the variable to let the main thread
  // know that we are done.
  {
    std::unique_lock<std::mutex> lck(done_mutex);
    done = true;
    cv.notify_one();
  }
}

int main() {
  alarm(60); // Kill the test if it hangs.

  // Install the signal handler
  struct sigaction sa;
  sa.sa_sigaction = SigprofHandler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART | SA_SIGINFO;
  if (sigaction(SIGPROF, &sa, 0) != 0) {
    fprintf(stderr, "failed to install signal handler\n");
    abort();
  }

  // Spawn a thread that will just loop and get the mutex lock:
  pthread_t thread;
  pthread_create(&thread, NULL, ThreadFunc, NULL);

  {
    // Lock the mutex before sending the signal
    std::lock_guard<std::mutex> guard(sampler_mutex);
    // From now on thread 1 will be waiting for the lock

    // Send the SIGPROF signal to thread.
    int r = pthread_kill(thread, SIGPROF);
    assert(r == 0);

    // Wait until signal handler sends the data.
    std::unique_lock lk(done_mutex);
    cv.wait(lk, [] { return done; });

    // We got the done variable from the signal handler. Exiting successfully.
    fprintf(stderr, "PASS\n");
  }

  // Wait for thread to prevent it from spinning on a released mutex.
  spin = false;
  pthread_join(thread, nullptr);
}

// CHECK-NOT: WARNING: ThreadSanitizer:
// CHECK: PASS