test_mutex.cpp 1.71 KB
Newer Older
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "lima/ThreadUtils.h"
#include "lima/Debug.h"
#include "lima/Exceptions.h"

using namespace lima;

DEB_GLOBAL(DebModTest);

class TestThread : public Thread
{
	DEB_CLASS(DebModTest, "TestThread");
public:
	enum Type { Tester, Locker, Releaser };
  
	TestThread(Type type) : m_type(type), m_started(false)
	{
		DEB_CONSTRUCTOR();
		DEB_PARAM() << DEB_VAR1(type);
	}

	void start()
	{
		DEB_MEMBER_FUNCT();
		Thread::start();
		AutoMutex l(m_cond.mutex());
		while (!m_started)
			m_cond.wait();
		DEB_TRACE() << "Main: started";
	}

protected:
	void threadFunction()
	{
		DEB_MEMBER_FUNCT();

		CleanUp cleanup(*this);

		if (m_type == Tester)
			THROW_COM_ERROR(Error) << "Testing cleanup";

		if (m_type == Locker) {
			AutoMutex l(m_mutex);
			l.leaveLocked();
			DEB_TRACE() << "Leave locked";
		} else {
			AutoMutex l(m_mutex, AutoMutex::PrevLocked);
			DEB_TRACE() << "Previously unlocked";
		}
	}

private:
	class CleanUp : public ExceptionCleanUp
	{
	public:
		using ExceptionCleanUp::ExceptionCleanUp;
		virtual ~CleanUp() {
			static_cast<TestThread&>(m_thread).signalStarted();
		}
	};

	void signalStarted()
	{
		DEB_MEMBER_FUNCT();
		AutoMutex l(m_cond.mutex());
		m_started = true;
		m_cond.signal();
		DEB_TRACE() << "Thread: started";
	}
	
	static Mutex m_mutex;
	Type m_type;
	Cond m_cond;
	bool m_started;
};

Mutex TestThread::m_mutex;

int main(int argc, char *argv[])
{
	DEB_GLOBAL_FUNCT();

	DebParams::setTypeFlags(DebParams::AllFlags);
	
	DEB_TRACE() << "Starting test";

	TestThread tester(TestThread::Tester);
	tester.start();
	tester.join();

	TestThread locker(TestThread::Locker);
	TestThread releaser(TestThread::Releaser);
	locker.start();
	releaser.start();
	locker.join();
	releaser.join();

	return 0;
}