-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy paththreadsafe.h
More file actions
70 lines (56 loc) · 1.66 KB
/
threadsafe.h
File metadata and controls
70 lines (56 loc) · 1.66 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <mutex>
#include "jsi/decorator.h"
#include "jsi/jsi.h"
namespace facebook {
namespace jsi {
class ThreadSafeRuntime : public Runtime {
public:
virtual void lock() const = 0;
virtual void unlock() const = 0;
virtual Runtime& getUnsafeRuntime() = 0;
};
namespace detail {
template <typename R, typename L>
struct WithLock {
L lock;
WithLock(R& r) : lock(r) {}
void before() { lock.lock(); }
void after() { lock.unlock(); }
};
// The actual implementation of a given ThreadSafeRuntime. It's parameterized
// by:
//
// - R: The actual Runtime type that this wraps
// - L: A lock type that has three members:
// - L(R& r) // ctor
// - void lock()
// - void unlock()
template <typename R, typename L>
class ThreadSafeRuntimeImpl final
: public WithRuntimeDecorator<WithLock<R, L>, R, ThreadSafeRuntime> {
public:
template <typename... Args>
ThreadSafeRuntimeImpl(Args&&... args)
: WithRuntimeDecorator<WithLock<R, L>, R, ThreadSafeRuntime>(unsafe_,
lock_),
unsafe_(std::forward<Args>(args)...),
lock_(unsafe_) {}
R& getUnsafeRuntime() override {
return WithRuntimeDecorator<WithLock<R, L>, R, ThreadSafeRuntime>::plain();
}
void lock() const override { lock_.before(); }
void unlock() const override { lock_.after(); }
private:
R unsafe_;
mutable WithLock<R, L> lock_;
};
} // namespace detail
} // namespace jsi
} // namespace facebook