File: Event.h

package info (click to toggle)
dolphin-emu 5.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 29,052 kB
  • sloc: cpp: 213,146; java: 6,252; asm: 2,277; xml: 1,998; ansic: 1,514; python: 462; sh: 279; pascal: 247; makefile: 124; perl: 97
file content (75 lines) | stat: -rw-r--r-- 1,606 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
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2014 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

// Multithreaded event class. This allows waiting in a thread for an event to
// be triggered in another thread. While waiting, the CPU will be available for
// other tasks.
// * Set(): triggers the event and wakes up the waiting thread.
// * Wait(): waits for the event to be triggered.
// * Reset(): tries to reset the event before the waiting thread sees it was
//            triggered. Usually a bad idea.

#pragma once

#ifdef _WIN32
#include <concrt.h>
#endif

#include <chrono>
#include <condition_variable>
#include <mutex>

#include "Common/Flag.h"

namespace Common {

class Event final
{
public:
	void Set()
	{
		if (m_flag.TestAndSet())
		{
			std::lock_guard<std::mutex> lk(m_mutex);
			m_condvar.notify_one();
		}
	}

	void Wait()
	{
		if (m_flag.TestAndClear())
			return;

		std::unique_lock<std::mutex> lk(m_mutex);
		m_condvar.wait(lk, [&]{ return m_flag.TestAndClear(); });
	}

	template<class Rep, class Period>
	bool WaitFor(const std::chrono::duration<Rep, Period>& rel_time)
	{
		if (m_flag.TestAndClear())
			return true;

		std::unique_lock<std::mutex> lk(m_mutex);
		bool signaled = m_condvar.wait_for(lk, rel_time,
			[&]{ return m_flag.TestAndClear(); });

		return signaled;
	}

	void Reset()
	{
		// no other action required, since wait loops on
		// the predicate and any lingering signal will get
		// cleared on the first iteration
		m_flag.Clear();
	}

private:
	Flag m_flag;
	std::condition_variable m_condvar;
	std::mutex m_mutex;
};

}  // namespace Common