Multi-thread program: Unhandled exception: Cannot allocate new fiber stack: Cannot allocate memory (Errno)

@orangeSi something like this maybe?

def test(num : Int32, ch, threads)
	num.times do |line|
        ch.send(line)
    end
end

def signal_finished(ch, count)
    count.times do
        ch.send(nil)
    end
end

def process(num : Int32)
    # Do something slow, sleep to simulate slow operation
    sleep(0.1)
end

def launch_workers(count)
    count.times do
        spawn do
            # When gets nil from the channel ends the working thread loop
            # ch.receive blocks until the channel has a message available to be read
            while line = ch.receive
                process(line)
            end
        end
    end
end

ch = Channel(Int32 | Nil).new
threads = 4
launch_workers(threads)

inf = ARGV[0].to_i

test(inf, ch)
signal_finished(ch,threads)
1 Like