15. require 'thread'
class ThreadExample
def initialize
@count = 0
@count_mutex = Mutex.new
# Start a few readers
threads = []
3.times do
threads << Thread.new do
read_values
end
end
threads.each(&:join)
end
...
ConcurrencyModels
2.Threaded/MutexExample
...
def read_values
loop do
@count_mutex.synchronize do
local_count = @count
# Get the "value"
local_count += rand(10)
@count = local_count
puts "Value: #{local_count}"
end
end
end
end
ThreadExample.new
Wednesday, July 10, 13
18. require 'socket'
server = TCPServer.open(host, port)
while client = server.accept
Thread.new do
line = client.gets
client.puts(line)
client.close
end
end
ConcurrencyModels
ThreadedEchoServer
Wednesday, July 10, 13
19. require 'eventmachine'
class Echo < EventMachine::Connection
def receive_data(data)
send_data(data)
end
end
EventMachine.run {
EventMachine.connect '127.0.0.1', 8081, Echo
}
ConcurrencyModels
Evented-io-EchoServer
Wednesday, July 10, 13
20. module ProxyConnection
def initialize(local_connection)
@local_connection = local_connection
end
def receive_data(data)
@local_connection.send_data(data)
end
end
module ProxyServer
def post_init
# Make a connection to the remote server
@connection = EventMachine.connect 'www.zeebly.com', 80, ProxyConnection, self
end
def receive_data(data)
@connection.send_data(data)
end
end
EventMachine::run do
EventMachine::start_server "127.0.0.1", 8080, ProxyServer
end
ConcurrencyModels
Evented-io-ProxyServer
Wednesday, July 10, 13