Thread and Queue

前端 未结 6 1462
情深已故
情深已故 2020-12-24 12:28

I am interested in knowing what would be the best way to implement a thread based queue.

For example:

I have 10 actions which I want to execute with only 4 t

6条回答
  •  情歌与酒
    2020-12-24 13:05

    Executable descriptive example:

    require 'thread'
    
    p tasks = [
        {:file => 'task1'},
        {:file => 'task2'},
        {:file => 'task3'},
        {:file => 'task4'},
        {:file => 'task5'}
    ]
    
    tasks_queue = Queue.new
    tasks.each {|task| tasks_queue << task}
    
    # run workers
    workers_count = 3
    workers = []
    workers_count.times do |n|
        workers << Thread.new(n+1) do |my_n|
            while (task = tasks_queue.shift(true) rescue nil) do
                delay = rand(0)
                sleep delay
                task[:result] = "done by worker ##{my_n} (in #{delay})"
                p task
            end
        end
    end
    
    # wait for all threads
    workers.each(&:join)
    
    # output results
    puts "all done"
    p tasks
    

提交回复
热议问题