Method: ALib::Util#threadify

Defined in:
lib/alib-0.5.0/util.rb

#threadify(list, n = 4, &b) ⇒ Object



1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
# File 'lib/alib-0.5.0/util.rb', line 1433

def threadify list, n = 4, &b
#--{{{
  n = Integer n
  done = Object.new.freeze
  jobs = Queue.new

  list.each_with_index{|elem, i| jobs.push [elem, i]}
  n.times{ jobs.push done} # mark the end

  consumers = Array.new n

  n.times do |i|
    consumers[i] = Thread.new do
      this = Thread.current
      this.abort_on_exception = true

      loop{
        job = jobs.pop
        this.exit if job == done
        jobs << (job << bcall(b, job))
      }
    end
  end

  consumers.map{|t| t.join}
  jobs.push done

  #sleep 5

  ret = Array.new list.size
  while((job = jobs.pop) != done)
    elem, i, value = job
    ret[i] = value
  end
  ret
#--}}}
end