forked from microsoft/cppwinrt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.cpp
More file actions
61 lines (49 loc) · 1.47 KB
/
thread_pool.cpp
File metadata and controls
61 lines (49 loc) · 1.47 KB
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
#include "pch.h"
using namespace winrt;
using namespace Windows::Foundation;
namespace
{
struct AsyncQueue
{
thread_pool m_pool;
AsyncQueue(uint32_t const high, uint32_t const low)
{
m_pool.thread_limits(high, low);
}
IAsyncAction Async(delegate<> callback)
{
co_await m_pool;
callback();
}
};
uint32_t test(uint32_t const iterations, uint32_t const high, uint32_t const low)
{
AsyncQueue queue(high, low);
std::vector<IAsyncAction> results;
uint32_t counter{};
for (uint32_t i = 0; i < iterations; ++i)
{
results.push_back(queue.Async([&]
{
auto value = counter + 1;
Sleep(10); // Induce thread pool to use more threads if available, also force race condition
counter = value;
}));
}
for (auto&& async : results)
{
async.get();
}
return counter;
}
}
TEST_CASE("thread_pool")
{
uint32_t const test_iterations = 100;
uint32_t const stable_counter = test(test_iterations, 1, 1);
uint32_t const unstable_counter = test(test_iterations, 10, 10);
// This is deterministic since the queue is single-threaded.
REQUIRE(stable_counter == test_iterations);
// This is unlikely to fail since the pool is multi-threaded.
REQUIRE(unstable_counter < test_iterations);
}