-
Notifications
You must be signed in to change notification settings - Fork 1
/
rtreq.rb
73 lines (60 loc) · 1.4 KB
/
rtreq.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env ruby
require 'rbczmq'
require_relative 'zhelpers'
context = ZMQ::Context.new
NUM_WORKERS = 10
class Worker
attr_accessor :socket
def initialize(context)
@socket = context.socket(ZMQ::REQ)
@socket.set_random_identity
@socket.connect("tcp://localhost:5671")
end
def run
total = 0
loop do
# tell the broker we're ready for work
@socket.send("Hi boss")
# Get workload from broker, until finished
work = @socket.recv
finished = (work == "Fired!")
if finished
puts "Completed #{total} tasks"
break
end
total += 1
sleep (rand(500)+1)/1000.0
end
end
end
def main(context)
broker = context.socket(ZMQ::ROUTER)
broker.bind("tcp://*:5671")
sleep(0.5)
NUM_WORKERS.times do
Thread.new do
worker = Worker.new(context)
worker.run
end
end
# run for five seconds and then tell works to end
end_time = Time.now + 5
workers_fired = 0
loop do
# next message gives us least recently used worker
identity = broker.recv
broker.recv # delimiter
broker.recv # worker response
broker.sendm(identity)
broker.sendm("")
# Encourage workers until it's time to fire them
if Time.now < end_time
broker.send("Work harder!")
else
broker.send("Fired!")
workers_fired += 1
break if workers_fired == NUM_WORKERS
end
end
end
main(context)