ref: b717d027b8f6705d6b6eb11dd6ea2ecd0c1cb980
dir: /Test_Multi_Threading.rb/
require 'thread'
require 'concurrent'
require 'async'
require 'async/http/internet'
class Echo
include Concurrent::Async
def echo(msg)
sleep(3)
print "#{msg}\n"
end
end
horn = Echo.new
horn.echo('zero') # synchronous, not thread-safe
# returns the actual return value of the method
horn.async.echo('one') # asynchronous, non-blocking, thread-safe
# returns an IVar in the :pending state
horn.async.echo('two') # synchronous, blocking, thread-safe
# returns an IVar in the :complete state
start = Time.now
Async do |task|
http_client = Async::HTTP::Internet.new
task.async do
http_client.get("https://httpbin.org/delay/1.6")
end
end
puts "Duration: #{Time.now - start}"
executor = Concurrent::ThreadPoolExecutor.new(
min_threads: 2,
max_threads: 5,
max_queue: 10
)
futures = []
5.times do |i|
futures << Concurrent::Future.execute(executor: executor) do
puts "Async task #{i} started"
sleep(rand(1..5))
puts "Async task #{i} finished"
end
end
futures.each(&:wait)
executor.shutdown
# Define a method that performs some asynchronous task
def async_task(name)
puts "Starting #{name}"
# Simulate some work
sleep(rand(5))
puts "#{name} completed"
end
# Create multiple threads for asynchronous execution
threads = []
threads << Thread.new { async_task('Task 1') }
threads << Thread.new { async_task('Task 2') }
threads << Thread.new { async_task('Task 3') }
# Wait for all threads to complete
threads.each(&:join)
puts "All tasks completed"
def Test
for i in 0..10 do
puts i
sleep(rand(0.1..1.0));
end
end
t1 = Thread.new{Test()}
t2 = Thread.new{Test()}
puts 'moz'
t1.join
t2.join