-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
74 lines (60 loc) · 1.23 KB
/
main.go
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
package main
import (
"fmt"
"sync"
"time"
)
type Table struct {
forks []*sync.RWMutex
}
type Philosopher struct {
name string
left byte
right byte
}
func newPhilosopher(name string, left, right byte) *Philosopher {
return &Philosopher{
name: name,
left: left,
right: right,
}
}
func (p *Philosopher) eat(table *Table) {
left := table.forks[p.left]
right := table.forks[p.right]
left.Lock()
defer left.Unlock()
time.Sleep(time.Duration(time.Millisecond * 150))
right.Lock()
defer right.Unlock()
fmt.Printf("%s начала есть\n", p.name)
time.Sleep(time.Second)
fmt.Printf("%s закончила есть\n", p.name)
}
func main() {
table := &Table{
forks: []*sync.RWMutex{
{},
{},
{},
{},
{},
},
}
philosophers := []*Philosopher{
newPhilosopher("Джудит Батлер", 0, 1),
newPhilosopher("Рая Дунаевская", 1, 2),
newPhilosopher("Зарубина Наталья", 2, 3),
newPhilosopher("Эмма Гольдман", 3, 4),
newPhilosopher("Анна Шмидт", 0, 4),
}
wg := sync.WaitGroup{}
wg.Add(len(philosophers))
for _, p := range philosophers {
go func(philosopher *Philosopher) {
defer wg.Done()
philosopher.eat(table)
}(p)
}
wg.Wait()
}