1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef FLUTTER_FML_SYNCHRONIZATION_SYNC_SWITCH_H_
6#define FLUTTER_FML_SYNCHRONIZATION_SYNC_SWITCH_H_
7
8#include <forward_list>
9#include <functional>
10#include <mutex>
11
12#include "flutter/fml/macros.h"
13
14namespace fml {
15
16/// A threadsafe structure that allows you to switch between 2 different
17/// execution paths.
18///
19/// Execution and setting the switch is exclusive, i.e. only one will happen
20/// at a time.
21class SyncSwitch {
22 public:
23 /// Represents the 2 code paths available when calling |SyncSwitch::Execute|.
24 struct Handlers {
25 /// Sets the handler that will be executed if the |SyncSwitch| is true.
26 Handlers& SetIfTrue(const std::function<void()>& handler);
27
28 /// Sets the handler that will be executed if the |SyncSwitch| is false.
29 Handlers& SetIfFalse(const std::function<void()>& handler);
30
31 std::function<void()> true_handler = [] {};
32 std::function<void()> false_handler = [] {};
33 };
34
35 /// Create a |SyncSwitch| with the false value.
36 SyncSwitch();
37
38 /// Create a |SyncSwitch| with the specified value.
39 ///
40 /// @param[in] value Default value for the |SyncSwitch|.
41 SyncSwitch(bool value);
42
43 /// Diverge execution between true and false values of the SyncSwitch.
44 ///
45 /// This can be called on any thread. Note that attempting to call
46 /// |SetSwitch| inside of the handlers will result in a self deadlock.
47 ///
48 /// @param[in] handlers Called for the correct value of the |SyncSwitch|.
49 void Execute(const Handlers& handlers);
50
51 /// Set the value of the SyncSwitch.
52 ///
53 /// This can be called on any thread.
54 ///
55 /// @param[in] value New value for the |SyncSwitch|.
56 void SetSwitch(bool value);
57
58 private:
59 std::mutex mutex_;
60 bool value_;
61
62 FML_DISALLOW_COPY_AND_ASSIGN(SyncSwitch);
63};
64
65} // namespace fml
66
67#endif // FLUTTER_FML_SYNCHRONIZATION_SYNC_SWITCH_H_
68