File: Flag.h

package info (click to toggle)
dolphin-emu 5.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 28,976 kB
  • ctags: 35,666
  • sloc: cpp: 213,139; java: 6,252; asm: 2,277; xml: 1,998; ansic: 1,514; python: 462; sh: 279; pascal: 247; makefile: 124; perl: 97
file content (62 lines) | stat: -rw-r--r-- 1,335 bytes parent folder | download | duplicates (2)
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
// Copyright 2014 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

// Abstraction for a simple flag that can be toggled in a multithreaded way.
//
// Simple API:
// * Set(bool = true): sets the Flag
// * IsSet(): tests if the flag is set
// * Clear(): clears the flag (equivalent to Set(false)).
//
// More advanced features:
// * TestAndSet(bool = true): sets the flag to the given value. If a change was
//                            needed (the flag did not already have this value)
//                            the function returns true. Else, false.
// * TestAndClear(): alias for TestAndSet(false).

#pragma once

#include <atomic>

namespace Common {

class Flag final
{
public:
	// Declared as explicit since we do not want "= true" to work on a flag
	// object - it should be made explicit that a flag is *not* a normal
	// variable.
	explicit Flag(bool initial_value = false) : m_val(initial_value) {}

	void Set(bool val = true)
	{
		m_val.store(val);
	}

	void Clear()
	{
		Set(false);
	}

	bool IsSet() const
	{
		return m_val.load();
	}

	bool TestAndSet(bool val = true)
	{
		bool expected = !val;
		return m_val.compare_exchange_strong(expected, val);
	}

	bool TestAndClear()
	{
		return TestAndSet(false);
	}

private:
	std::atomic_bool m_val;
};

}  // namespace Common