-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.cpp
More file actions
executable file
·73 lines (65 loc) · 1.45 KB
/
mutex.cpp
File metadata and controls
executable file
·73 lines (65 loc) · 1.45 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
62
63
64
65
66
67
68
69
70
71
72
73
/**
* mutex.cpp
*
* EECS 482: Project 2, Winter 2019
*
* Jiajun Peng, Youwei Chen, Xuetong Sun
* pjiajun, skylarch, xuetong
*
*/
#include "mutex.h"
#include "mutex_impl.h"
#include "cpu.h"
#include "cpu_impl.h"
#include <queue>
#include <stdexcept>
/**
* Effects: Create mutex object.
*/
mutex::mutex() {
try {
impl_ptr = new impl;
impl_ptr->owner = -1;
}
catch (std::bad_alloc& alloc_error) {
assert_interrupts_disabled();
cpu::interrupt_enable();
throw alloc_error;
}
}
/**
* Modifies: block_queue, mutex ownership.
* Effects: Acquire mutex if it is free,
or goes to the block queue of the mutex.
*/
void mutex::lock() {
assert_interrupts_enabled();
cpu::interrupt_disable();
if (impl_ptr->owner != -1) {
impl_ptr->block_queue.push(cpu::self()->impl_ptr->current_thread);
cpu::impl::switch_thread();
}
else {
impl_ptr->owner = cpu::self()->impl_ptr->current_thread->thread_id;
}
assert_interrupts_disabled();
cpu::interrupt_enable();
}
/**
* Modifies: block_queue, ready_queue, mutex ownership.
* Effects: Unlock mutex.
*/
void mutex::unlock() {
assert_interrupts_enabled();
cpu::interrupt_disable();
impl_ptr->unlock_helper();
assert_interrupts_disabled();
cpu::interrupt_enable();
}
/**
* Effects: Delete mutex object.
*/
mutex::~mutex(){
delete impl_ptr;
impl_ptr = nullptr;
}