-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathqueued_task.h
More file actions
59 lines (48 loc) · 1.9 KB
/
queued_task.h
File metadata and controls
59 lines (48 loc) · 1.9 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
#pragma once
#include <type_traits>
#include <memory>
namespace vi {
// Base interface for asynchronously executed tasks.
// The interface basically consists of a single function, run(), that executes
// on the target queue. For more details see the run() method and TaskQueue.
class QueuedTask {
public:
virtual ~QueuedTask() = default;
// Main routine that will run when the task is executed on the desired queue.
// The task should return |true| to indicate that it should be deleted or
// |false| to indicate that the queue should consider ownership of the task
// having been transferred. Returning |false| can be useful if a task has
// re-posted itself to a different queue or is otherwise being re-used.
virtual bool run() = 0;
};
// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
template <typename Closure>
class ClosureTask : public QueuedTask {
public:
explicit ClosureTask(Closure&& closure)
: closure_(std::forward<Closure>(closure)) {}
private:
bool run() override {
closure_();
return true;
}
typename std::decay<Closure>::type closure_;
};
template <typename Closure>
std::unique_ptr<QueuedTask> ToQueuedTask(Closure&& closure) {
return std::make_unique<ClosureTask<Closure>>(std::forward<Closure>(closure));
}
// Extends ClosureTask to also allow specifying cleanup code.
// This is useful when using lambdas if guaranteeing cleanup, even if a task
// was dropped (queue is too full), is required.
template <typename Closure, typename Cleanup>
class ClosureTaskWithCleanup : public ClosureTask<Closure> {
public:
ClosureTaskWithCleanup(Closure&& closure, Cleanup&& cleanup)
: ClosureTask<Closure>(std::forward<Closure>(closure))
, cleanup_(std::forward<Cleanup>(cleanup)) {}
~ClosureTaskWithCleanup() override { cleanup_(); }
private:
typename std::decay<Cleanup>::type cleanup_;
};
}