-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
61 lines (45 loc) · 1.27 KB
/
main.cpp
File metadata and controls
61 lines (45 loc) · 1.27 KB
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
#include "Thread.h"
#include "MyThread.h"
#include "Mutex.h"
class MutexTest : public Thread
{
public:
MutexTest (Mutex& mutexobj): mutex(mutexobj) {}
void* run ()
{
cout << "Thread" << (unsigned long int)self() << " is waiting for the mutex" << endl;
mutex.lock ();
cout << "Thread" << (unsigned long int)self() << " acquired the mutex" << endl;
sleep (10);
mutex.unLock();
cout << "Thread" << (unsigned long int)self() << " unlocked the mutex" << endl;
return NULL;
}
private:
Mutex &mutex;
};
int main (int argc, char **argv)
{
MyThread* thread1 = new MyThread;
MyThread* thread2 = new MyThread;
thread1 -> start ();
thread2 -> start ();
thread1 -> join ();
thread2 -> join ();
thread1 -> detach ();
thread2 -> detach ();
delete thread1;
delete thread2;
Mutex mutex;
MutexTest mTest(mutex);
mTest.start ();
cout << "Main Thread is waiting for the mutex" << endl;
mutex.lock ();
cout << "Main Thread acquired the mutex" << endl;
sleep (5);
mutex.unLock ();
cout << "Main Thread unlocked the mutex" << endl;
//tells the main thread should wait for the spawned thread completes its execution.
mTest.join ();
return 0;
}