9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[メモ]Railsで並列処理をしてみた

Last updated at Posted at 2017-01-04

概要

Parallelが簡単そうだったけど、Couldn't cleanly terminate allみたいなエラーはいたのでQueueで実装。
新しいGemをインストールする必要がないのもいい。

参考にした記事はすべてThreadを2にしてたんだけど、適切なThread数がわからなかった。
追記:スクレイピングの処理をMacBook Pro プロセッサ 2.7 GHz Intel Core i5 で走らせてみた結果、3の場合が一番早かった。

サンプル

lib/tasks/parallel_sample.rake
namespace :parallel do
   task sample: :environment
      queue = Queue.new
      nodes.each { |i| queue.push(i) }
      queue.push(nil)

      Array.new(3) do |i|
        Thread.new do
          begin
            while num = queue.pop(true)
              # コネクション数の増大を防ぐ
              ActiveRecord::Base.connection_pool.with_connection do
                p num
                User.all.sample.update(value: num)
                sleep 0.5
                puts "end #{num}"
              end
            end

            queue.push nil
          end
        end
      end.each(&:join)
      p "end!!!!!"
  end
end
$ bundle exec rake parallel:sample
0
1
2
end 2
end 0
end 1
3
4
5
end 3
end 5
6
end 4
7
8
end 6
end 8
10
end 7
11
9
end 10
12
end 9
13
end 11
14
end 12
end 13
end 14
15
16
17
end 15
end 17
end 16
18
20
19
end 18
end 20
end 19
21
22
23
end 21
24
end 22
25
end 23
26
end 24
end 25
end 26
29
27
28
end 29
end 28
end 27
30
end 30
"end!!!!!"

参考

Rubyで並列処理が簡単にできるgem parallel - 酒と泪とRubyとRailsと http://morizyun.github.io/blog/parallel-process-ruby-gem/ @zyunnosukeさんから

【Ruby on Rails】非同期処理についてその②。 〜マルチスレッドとかマルチプロセスを実装してみた〜 - (ΦωΦ) http://shirusu-ni-tarazu.hatenablog.jp/entry/2013/07/02/042448 @711fumiさんから

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?