1 // RUN: %clang_tsan %s -lstdc++ -o %t && %run %t 2>&1 | FileCheck %s
5 #include <linux/futex.h>
9 #include <sys/syscall.h>
15 #include <sanitizer/linux_syscall_hooks.h>
17 int futex(int *uaddr
, int futex_op
, int val
, const struct timespec
*timeout
,
18 int *uaddr2
, int val3
) {
19 __sanitizer_syscall_pre_futex(uaddr
, futex_op
, val
, timeout
, uaddr2
, val3
);
20 int result
= syscall(SYS_futex
, uaddr
, futex_op
, val
, timeout
, uaddr2
, val3
);
21 __sanitizer_syscall_post_futex(result
, uaddr
, futex_op
, val
, timeout
, uaddr2
,
26 // Simple mutex implementation using futex.
33 while ((c
= __sync_val_compare_and_swap(&value
, 0, 1)) != 0) {
36 int r
= futex(&value
, FUTEX_WAIT_PRIVATE
, 1, nullptr, nullptr, 0);
37 if (r
== -1 && errno
!= EAGAIN
) {
38 fprintf(stderr
, "futex wait error\n");
46 int r
= futex(&value
, FUTEX_WAKE_PRIVATE
, 1, nullptr, nullptr, 0);
48 fprintf(stderr
, "futex wake error\n");
59 void *Thread(void *x
) {
60 // Waiting for the futex.
66 static void SigprofHandler(int signal
, siginfo_t
*info
, void *context
) {
71 void InstallSignalHandler() {
73 sa
.sa_sigaction
= SigprofHandler
;
74 sigemptyset(&sa
.sa_mask
);
75 sa
.sa_flags
= SA_RESTART
| SA_SIGINFO
;
76 if (sigaction(SIGPROF
, &sa
, 0) != 0) {
77 fprintf(stderr
, "failed to install signal handler\n");
83 alarm(60); // Kill the test if it hangs.
85 // Install the signal handler
86 InstallSignalHandler();
88 // Lock the futex at first so the other thread will wait for it.
91 // Create the thread to wait for the futex.
93 pthread_create(&thread
, NULL
, Thread
, NULL
);
95 // Just waiting a bit to make sure the thead is at the FUTEX_WAIT_PRIVATE
97 std::this_thread::sleep_for(std::chrono::milliseconds(100));
99 // Send the signal to the other thread, which will send the futex wake
101 int r
= pthread_kill(thread
, SIGPROF
);
104 // Futex should be notified and the thread should be able to continue.
105 pthread_join(thread
, NULL
);
107 // Exiting successfully.
108 fprintf(stderr
, "PASS\n");
112 // CHECK-NOT: WARNING: ThreadSanitizer: