-
Notifications
You must be signed in to change notification settings - Fork 314
/
Copy patherrno_test.cpp
69 lines (57 loc) · 2.1 KB
/
errno_test.cpp
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
#include <userver/utest/utest.hpp>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <vector>
#include <userver/engine/async.hpp>
#include <userver/engine/deadline.hpp>
#include <userver/engine/sleep.hpp>
#include <userver/engine/task/cancel.hpp>
#include <userver/engine/task/task_with_result.hpp>
USERVER_NAMESPACE_BEGIN
namespace {
constexpr size_t kNumThreads = 2;
} // namespace
UTEST_MT(Errno, IsCoroLocal, kNumThreads) {
size_t threads_started{0};
size_t threads_switched{0};
std::mutex mutex;
std::condition_variable cv;
std::vector<engine::TaskWithResult<bool>> tasks;
auto deadline = engine::Deadline::FromDuration(utest::kMaxTestWaitTime);
for (size_t i = 0; i < kNumThreads; ++i) {
tasks.push_back(engine::AsyncNoSpan([&] {
{
// ensure every task gets its own thread
std::unique_lock lock(mutex);
++threads_started;
cv.wait_for(lock, deadline.TimeLeft(), [&] { return threads_started >= kNumThreads; });
cv.notify_all();
}
const auto init_thread_id = std::this_thread::get_id();
const auto* init_errno_ptr = &errno;
// if attribute `const` is used all subsequent `errno` TLS accesses
// may be optimized out
while (!engine::current_task::IsCancelRequested() && !deadline.IsReached()) {
if (std::this_thread::get_id() != init_thread_id) {
// lock this thread until all others switch as well
std::unique_lock lock(mutex);
++threads_switched;
cv.wait_for(lock, deadline.TimeLeft(), [&] { return threads_switched >= kNumThreads; });
cv.notify_all();
return &errno != init_errno_ptr;
} else {
engine::Yield();
}
}
return false;
}));
}
for (auto& task : tasks) {
EXPECT_TRUE(task.Get());
}
}
USERVER_NAMESPACE_END