1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 #include <atomic>
20 #include <thread>
21 #include <utility>
22
23 namespace android::mediautils {
24
25 namespace impl {
26 class stop_source;
27 /**
28 * Const view on stop source, which the running thread uses and an interface
29 * for cancellation.
30 */
31 class stop_token {
32 public:
stop_token(const stop_source & source)33 stop_token(const stop_source& source) : stop_source_(source) {}
34 bool stop_requested() const;
35
36 private:
37 const stop_source& stop_source_;
38 };
39
40 class stop_source {
41 public:
get_token()42 stop_token get_token() { return stop_token{*this}; }
stop_requested()43 bool stop_requested() const { return cancellation_signal_.load(); }
request_stop()44 bool request_stop() {
45 auto f = false;
46 return cancellation_signal_.compare_exchange_strong(f, true);
47 }
48
49 private:
50 std::atomic_bool cancellation_signal_ = false;
51 };
52
stop_requested()53 inline bool stop_token::stop_requested() const {
54 return stop_source_.stop_requested();
55 }
56 } // namespace impl
57
58 using stop_token = impl::stop_token;
59 /**
60 * Just a jthread, since std::jthread is still experimental in our toolchain.
61 * Implements a subset of essential functionality (co-op cancellation and join on dtor).
62 * If jthread gets picked up, usage can be cut over.
63 */
64 class jthread {
65 public:
66 /**
67 * Construct/launch and thread with a callable which consumes a stop_token.
68 * The callable must be cooperatively cancellable via stop_token::stop_requested(), and will be
69 * automatically stopped then joined on destruction.
70 * Example:
71 * jthread([](stop_token stok) {
72 * while(!stok.stop_requested) {
73 * // do work
74 * }
75 * }
76 */
77 template <typename F>
jthread(F && f)78 jthread(F&& f) : stop_source_{}, thread_{std::forward<F>(f), stop_source_.get_token()} {}
79
~jthread()80 ~jthread() {
81 stop_source_.request_stop();
82 thread_.join();
83 }
84
request_stop()85 bool request_stop() { return stop_source_.request_stop(); }
86
87 private:
88 // order matters
89 impl::stop_source stop_source_;
90 std::thread thread_;
91 };
92 } // namespace android::mediautils
93