-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsleep_sort.hpp
More file actions
81 lines (73 loc) · 2.27 KB
/
Copy pathsleep_sort.hpp
File metadata and controls
81 lines (73 loc) · 2.27 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#pragma once
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <future>
#include <iterator>
#include <thread>
#include <vector>
/// @brief Asynchronously sorts a range of integral types by sleeping until it's
/// time to add a value. Implemented using std::thread
/// @param first Iterator to the first element in the range
/// @param last Iterator one past the end of the range
template<
typename Iterator,
std::enable_if_t<
std::is_integral_v<typename std::iterator_traits<Iterator>::value_type>,
std::nullptr_t> = nullptr>
auto
sleep_sort_thread(Iterator first, Iterator last) -> void
{
if (first == last) {
return;
}
using ValueType = typename std::iterator_traits<Iterator>::value_type;
std::vector<std::thread> threads;
Iterator result = first;
const auto min = *std::min_element(first, last);
const auto now = std::chrono::steady_clock::now();
for (Iterator iter = first; iter != last; ++iter) {
threads.push_back(std::thread(
[&result, &now, &min](ValueType val) {
std::this_thread::sleep_until(now + std::chrono::seconds(val - min));
*result = val;
++result;
},
*iter));
}
for (auto& thread : threads) {
if (thread.joinable()) {
thread.join();
}
}
}
/// @brief Asynchronously sorts a range of integral types by sleeping until it's
/// time to add a value. Implemented using std::async
/// @param first Iterator to the first element in the range
/// @param last Iterator one past the end of the range
template<
typename Iterator,
std::enable_if_t<
std::is_integral_v<typename std::iterator_traits<Iterator>::value_type>,
std::nullptr_t> = nullptr>
auto
sleep_sort_async(Iterator first, Iterator last) -> void
{
if (first == last) {
return;
}
using ValueType = typename std::iterator_traits<Iterator>::value_type;
std::vector<std::future<void>> futures;
Iterator result = first;
const auto min = *std::min_element(first, last);
const auto now = std::chrono::steady_clock::now();
for (Iterator iter = first; iter != last; ++iter) {
futures.emplace_back(std::async(
[&result, &now, &min](ValueType val) {
std::this_thread::sleep_until(now + std::chrono::seconds(val - min));
*result = val;
++result;
},
*iter));
}
}