blob: a6d845ce4aa2c85284b07674ac4d7fdc60728868 (
plain)
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
|
#include <mbgl/storage/request.hpp>
#include <mbgl/map/environment.hpp>
#include <mbgl/storage/response.hpp>
#include <mbgl/util/util.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/uv_detail.hpp>
#include <cassert>
#include <functional>
namespace mbgl {
struct Request::Canceled { std::mutex mutex; bool confirmed = false; };
// Note: This requires that loop is running in the current thread (or not yet running).
Request::Request(const Resource &resource_, uv_loop_t *loop, Callback callback_)
: async(util::make_unique<uv::async>(loop, [this] { notifyCallback(); })),
callback(callback_),
resource(resource_) {
}
// Called in the originating thread.
void Request::notifyCallback() {
if (!canceled) {
invoke();
} else {
bool destroy = false;
{
std::unique_lock<std::mutex> lock(canceled->mutex);
destroy = canceled->confirmed;
}
// Don't delete right way, because we have to unlock the mutex before deleting.
if (destroy) {
delete this;
}
}
}
void Request::invoke() {
assert(response);
// The user could supply a null pointer or empty std::function as a callback. In this case, we
// still do the file request, but we don't need to deliver a result.
if (callback) {
callback(*response);
}
delete this;
}
Request::~Request() = default;
// Called in the FileSource thread.
void Request::notify(const std::shared_ptr<const Response> &response_) {
assert(!response);
response = response_;
assert(response);
async->send();
}
// Called in the originating thread.
void Request::cancel() {
assert(async);
assert(!canceled);
canceled = util::make_unique<Canceled>();
}
// Called in the FileSource thread.
// Will only ever be invoked after cancel() was called in the original requesting thread.
void Request::destruct() {
assert(async);
assert(canceled);
std::unique_lock<std::mutex> lock(canceled->mutex);
canceled->confirmed = true;
async->send();
// after this method returns, the FileSource thread has no knowledge of
// this object anymore.
}
}
|