-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetached_task.h
67 lines (52 loc) · 1.9 KB
/
detached_task.h
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
#pragma once
// MIT License - Copyright(c) 2019 Christian Deneke see LICENSE file
#include <memory>
#include <future>
// The detached_task::execute funtion is a work around to allow fire and forget tasks
// without spawning a new thread every time. Instead it relies on the internal thread
// pool of std::async to perform the task.
// Example:
//
// detached_task::execute( [](){std::cout<<"hello world\n";} );
//
// NOTE:
// While tasks spawned before leaving main will be waited for before the process terminates,
// no new tasks may be created once main is left.
namespace detached_task {
// internal namespace taking care of storing and "disposing"
// of std::futures generated by std::async calls
namespace detail {
using Future_container = std::vector<std::future<void>>;
constexpr size_t max_pending_futures = 30;
static std::mutex detached_task_lock;
static void future_consumer(std::future<void>&& new_future)
{
std::lock_guard<decltype(detached_task_lock)> guard(detached_task_lock);
static Future_container futures;
// add the future to the pending list
futures.emplace_back(std::move(new_future));
if (futures.size() > max_pending_futures)
{
// if the limit of pending futures is exceeded,
// spawn a separate task to "await" all of them
Future_container temp;
// swap futures into temp container to be able to
// move and still add the new task to futures
temp.swap(futures);
// enqueue the new task whose only job is to wait
// for all other tasks
futures.emplace_back(
std::async(std::launch::async,
[d = std::move(temp)](){; })
);
}
}
} // detail namespace
template <class Task>
void execute(Task&& new_task)
{
detail::future_consumer(
std::async(std::launch::async, std::move(new_task))
);
}
} // namespace detached_task