Prev | Current Page 372 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


The following example shows a threaded example (each time you run this, the results are
likely to be displayed in a different order, as the threads end at various and slightly random
times):
# Threaded example using concurrency
require 'rubygems'
require_gem 'activerecord'
ActiveRecord::Base.establish_connection(:adapter => "mysql",
:database => "testdb", :username => "root", :password => "", :host => "localhost")
ActiveRecord::Base.allow_concurrency = true
class Direct < ActiveRecord::Base
end
threads = []
20.times do |i|
t = Thread.new do
data = Direct.find(i + 1)
puts "Thread: #{i} #{data.contact_email}"
end
threads.push(t)
end
threads.each {|t| t.join }
The preceding example assumes, of course, that you have a table called directs with at
least the 20 records we reference (ids with values from 1 to 20). It??™s also important to note that
the preceding example is just a generic example of a threaded application where one process
manages the single database connection intelligently for a concurrent process.


Pages:
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384