-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore.c
82 lines (67 loc) · 1.98 KB
/
semaphore.c
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
#include <block.h>
#include <sched.h>
#include <semaphore.h>
struct sem_group semaphore_groups[NR_TASKS / 2];
extern struct list_head free_semaphore_group_queue;
void init_sems() {
INIT_LIST_HEAD(&free_semaphore_group_queue);
for (int i = 0; i < NR_TASKS / 2; ++i) {
for (int j = 0; j < NR_SEMS; ++j) {
initialize_semaphore(&(semaphore_groups[i].semaphores[j]));
}
list_add(
&semaphore_groups[i].semaphore_group_anchor,
&free_semaphore_group_queue);
}
}
void initialize_semaphore(struct sem *s) {
s->owner_TID = -1;
INIT_LIST_HEAD(&s->blocked_anchor);
}
struct sem_group *assign_semaphore_group(struct task_struct *p) {
if (list_empty(&free_semaphore_group_queue))
return 0;
struct list_head *sem_group_head = list_first(&free_semaphore_group_queue);
struct sem_group *group =
list_entry(sem_group_head, struct sem_group, semaphore_group_anchor);
list_del(sem_group_head);
struct list_head *e;
list_for_each(e, &p->thread_anchor) {
struct task_struct *thread =
list_entry(e, struct task_struct, thread_anchor);
thread->sem_group = group;
}
p->sem_group = group;
return group;
}
int unassign_semaphore_group(struct task_struct *p) {
if (p->sem_group == 0)
return -1;
list_add(&p->sem_group->semaphore_group_anchor, &free_semaphore_group_queue);
struct list_head *e;
list_for_each(e, &p->thread_anchor) {
struct task_struct *thread =
list_entry(e, struct task_struct, thread_anchor);
thread->sem_group = 0;
}
return 0;
}
struct sem *get_semaphore(sem_t *s) {
int sem_number = (int)s;
if (current()->sem_group == 0)
return 0;
if (sem_number < 0 || sem_number > NR_SEMS)
return 0;
return ¤t()->sem_group->semaphores[sem_number];
}
int unblock_blocked_semaphore_threads(struct sem *s) {
struct list_head *e;
struct list_head *tmp;
int cont = 0;
list_for_each_safe(e, tmp, &s->blocked_anchor) {
if (unblock(e) < 1)
return -1;
++cont;
}
return cont;
}