95 lines
2 KiB
Julia
95 lines
2 KiB
Julia
mutable struct Philosopher
|
|
name::String
|
|
righthanded::Bool
|
|
rightfork::Channel
|
|
leftfork::Channel
|
|
|
|
function Philosopher(name, leftfork, rightfork, righthanded)
|
|
this = new()
|
|
this.name = name
|
|
this.righthanded = righthanded
|
|
this.leftfork = leftfork
|
|
this.rightfork = rightfork
|
|
this
|
|
end
|
|
end
|
|
|
|
mutable struct Table
|
|
fork0::Channel
|
|
fork1::Channel
|
|
fork2::Channel
|
|
fork3::Channel
|
|
fork4::Channel
|
|
function Table()
|
|
this = new()
|
|
this.fork0 = Channel(1)
|
|
put!(this.fork0, "fork")
|
|
|
|
this.fork1 = Channel(1)
|
|
put!(this.fork1, "fork")
|
|
|
|
this.fork2 = Channel(1)
|
|
put!(this.fork2, "fork")
|
|
|
|
this.fork3 = Channel(1)
|
|
put!(this.fork3, "fork")
|
|
|
|
this.fork4 = Channel(1)
|
|
put!(this.fork4, "fork")
|
|
this
|
|
end
|
|
end
|
|
|
|
table = Table();
|
|
tasks = [
|
|
Philosopher("Philosopher 1", table.fork0, table.fork1, false),
|
|
Philosopher("Philosopher 2", table.fork1, table.fork2, true),
|
|
Philosopher("Philosopher 3", table.fork2, table.fork3, true),
|
|
Philosopher("Philosopher 4", table.fork3, table.fork4, true),
|
|
Philosopher("Philosopher 5", table.fork4, table.fork0, true)
|
|
]
|
|
|
|
hunger = 20
|
|
thinktime = 0.1
|
|
eattime = 0.1
|
|
|
|
function philosopher(p, t)
|
|
println("$(p.name) has seated")
|
|
for _ in hunger:-1:0
|
|
println("$(p.name) is hungry")
|
|
|
|
if p.righthanded
|
|
take!(p.rightfork);
|
|
take!(p.leftfork);
|
|
else
|
|
take!(p.leftfork);
|
|
take!(p.rightfork);
|
|
end
|
|
|
|
println("$(p.name) is eating")
|
|
sleep(eattime * rand())
|
|
|
|
put!(p.rightfork, "fork")
|
|
put!(p.leftfork, "fork")
|
|
|
|
println("$(p.name) is thinking")
|
|
sleep(thinktime * rand())
|
|
end
|
|
println("$(p.name) is satisfied")
|
|
|
|
println("(!) $(p.name) left the table")
|
|
end
|
|
|
|
function runall(tasklist)
|
|
c = Condition()
|
|
|
|
for p in tasklist
|
|
@async (philosopher(p, table); notify(c))
|
|
end
|
|
|
|
for p in tasklist
|
|
wait(c)
|
|
end
|
|
end
|
|
|
|
runall(tasks)
|