Skip to content

Commit

Permalink
Scheduler: don't resume dead fibers and the @current fiber, fixes cry…
Browse files Browse the repository at this point in the history
  • Loading branch information
forksaber committed Jan 30, 2019
1 parent fb39000 commit 0cdea03
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
59 changes: 59 additions & 0 deletions spec/std/concurrent/select_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,63 @@ describe "select" do
sleep
x.should eq 1
end

it "select with buffered shouldn't segfault on resuming already completed fiber, fixed #3900" do
ch1 = Channel::Buffered(Int32).new(1)
ch2 = Channel::Buffered(Int32).new(1)
res = [] of Int32

spawn do
3.times do
select
when x = ch1.receive
res << x
when y = ch2.receive
res << y
end
end
end

spawn do
3.times do |i|
select
when ch1.send(1)
when ch2.send(2)
end
end
end

sleep 0
res.should eq([1, 2, 1])
end

it "select with buffered channels shouldn't segfault when current fiber resumes itself" do
ch1 = Channel::Buffered(Int32).new(1)
ch2 = Channel::Buffered(Int32).new(1)
res = [] of Int32

spawn do
3.times do
select
when x = ch1.receive
res << x
when y = ch2.receive
res << y
end
end
end

spawn do
3.times do |i|
select
when ch1.send(1)
when ch2.send(2)
end
end
sleep 0
end

sleep 0
res.should eq([1, 2, 1])
end
end
6 changes: 5 additions & 1 deletion src/crystal/scheduler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ class Crystal::Scheduler
end

protected def reschedule : Nil
if runnable = @runnables.shift?
while runnable = @runnables.shift?
next if runnable == @current
break if runnable.alive
end
if runnable
runnable.resume
else
Crystal::EventLoop.resume
Expand Down
2 changes: 2 additions & 0 deletions src/fiber.cr
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ class Fiber

# :nodoc:
property previous : Fiber?
property alive : Bool = true

# :nodoc:
def self.inactive(fiber : Fiber)
Expand Down Expand Up @@ -155,6 +156,7 @@ class Fiber
ex.inspect_with_backtrace(STDERR)
STDERR.flush
ensure
@alive = false
@@stack_pool << @stack

# Remove the current fiber from the linked list
Expand Down

0 comments on commit 0cdea03

Please sign in to comment.