-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparallel_hash.rb
48 lines (36 loc) · 921 Bytes
/
parallel_hash.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
require 'thread'
require 'digest/md5'
# For motivation on why you might want to do all this hashing, see:
# https://en.wikipedia.org/wiki/Hashcash
# Thread::abort_on_exception = true
t1 = Time.now
MAXIMUM = 2 ** 128 - 1
DIFFICULTY = 1_000_000.0
GOAL = (MAXIMUM / DIFFICULTY)
NUM_HASHES = 5
NUM_THREADS = 8
def start_thread(thread_idx, queue)
thread = Thread.new do
# inside the block is the code the thread runs. Then the thread quits.
string = "#{thread_idx}"
while true
hash = Digest::MD5.hexdigest(string).to_i(16)
if hash < GOAL
queue << [string, hash]
end
string = hash.to_s
end
end
thread
end
# "thread safe" queue
queue = Queue.new
threads = []
NUM_THREADS.times { |thread_idx| threads << start_thread(thread_idx, queue) }
NUM_HASHES.times do
result = queue.shift
p result
end
threads.each { |thread| thread.kill }
t2 = Time.now
puts t2 - t1