Skip to content

Instantly share code, notes, and snippets.

@dsisnero
Forked from Inversion-des/correct_workers_pool.rb
Created February 1, 2021 23:57
Show Gist options
  • Save dsisnero/7edd3317be45681a690e11464300aabe to your computer and use it in GitHub Desktop.
Save dsisnero/7edd3317be45681a690e11464300aabe to your computer and use it in GitHub Desktop.
require 'openssl'
require 'base64'
# calibrate numbers to get 1s or 10s in solo
N = 48
DATA_SIZE = 600_000
workers_N = 2
# prepare static data set
DATA_ARR = N.times.map do |n|
(n.to_s * DATA_SIZE).freeze
end.freeze
# encryption/dectyption helper
class BaseCryptor
def initialize
@encryptor = cipher_base.encrypt.tap do |o|
@key = o.random_key
@iv = o.random_iv
end
@decryptor = cipher_base.decrypt.tap do |o|
o.key = @key
o.iv = @iv
end
end
def cipher_base
OpenSSL::Cipher.new 'AES-256-CBC'.freeze
end
def encrypt(text)
@encryptor.reset
encrypted_text = @encryptor.update(text) + @encryptor.final
Base64.encode64 encrypted_text
end
def decrypt(encrypted_text_b64)
encrypted_text = Base64.decode64 encrypted_text_b64
@decryptor.reset
decrypted_text = @decryptor.update(encrypted_text) + @decryptor.final
end
end
def workload(cryptor, n)
# puts \
enc = cryptor.encrypt DATA_ARR[n]
# puts \
res = cryptor.decrypt enc
fail 'MATCH ERROR' if res != DATA_ARR[n]
# sleep 5 if n == 3
end
puts 'in the main thread'
t_start = Time.now
@cryptor = BaseCryptor.new
N.times do |n|
workload @cryptor, n
end
puts "Total: %.3f" % (Time.now - t_start)
puts
# prepare workers pool
workers_N.times do
Ractor.new do
cryptor = BaseCryptor.new
loop do
n = ((( Ractor.main.take ))) # <-- from main
workload cryptor, n
Ractor.main << 'done %d' % n
end
end
end
puts "in #{workers_N} ractors"
t_start = Time.now
# issue tasks
N.times do |n|
((( Ractor.yield n ))) # --> to workers
end
# wait for all tasks done
N.times do
# puts \
((( Ractor.recv ))) # <-- from workers
end
puts "Total: %.3f" % (Time.now - t_start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment