summaryrefslogtreecommitdiff
path: root/libcxx/test/libcxx/thread/thread.stoptoken/atomic_unique_lock.pass.cpp
blob: b8ee91c041261e551bde2f9eee6177a34f724ac0 (plain)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: no-threads

// XFAIL: availability-synchronization_library-missing

// UNSUPPORTED: c++03, c++11, c++14, c++17
// ADDITIONAL_COMPILE_FLAGS: -Wno-private-header

#include <__stop_token/atomic_unique_lock.h>
#include <atomic>
#include <cassert>
#include <chrono>
#include <thread>

#include "make_test_thread.h"
#include "test_macros.h"

template <uint8_t LockBit>
void test() {
  using Lock = std::__atomic_unique_lock<uint8_t, LockBit>;

  // lock on constructor
  {
    std::atomic<uint8_t> state{0};
    Lock l(state);
    assert(l.__owns_lock());
  }

  // always give up locking
  {
    std::atomic<uint8_t> state{0};
    Lock l(state, [](auto const&) { return true; });
    assert(!l.__owns_lock());
  }

  // test overload that has custom state after lock
  {
    std::atomic<uint8_t> state{0};
    auto neverGiveUpLocking = [](auto const&) { return false; };
    auto stateAfter         = [](auto) { return uint8_t{255}; };
    Lock l(state, neverGiveUpLocking, stateAfter, std::memory_order_acq_rel);
    assert(l.__owns_lock());
    assert(state.load() == 255);
  }

  // lock and unlock
  {
    std::atomic<uint8_t> state{0};
    Lock l(state);
    assert(l.__owns_lock());

    l.__unlock();
    assert(!l.__owns_lock());

    l.__lock();
    assert(l.__owns_lock());
  }

  // lock blocking
  {
    std::atomic<uint8_t> state{0};
    int i = 0;
    Lock l1(state);

    auto thread1 = support::make_test_thread([&] {
      std::this_thread::sleep_for(std::chrono::milliseconds{10});
      i = 5;
      l1.__unlock();
    });

    Lock l2(state);
    // l2's lock has to wait for l1's unlocking
    assert(i == 5);

    thread1.join();
  }
}

int main(int, char**) {
  test<1 << 0>();
  test<1 << 1>();
  test<1 << 2>();
  test<1 << 3>();
  test<1 << 4>();
  test<1 << 5>();
  test<1 << 6>();
  test<1 << 7>();
  return 0;
}