0

我经常使用 Thread,我想知道这是否是一个好习惯:

    def self.create_all_posts
      threads = []
      self.fetch_all_posts.each do |e|
        if e.present?
          threads << Thread.new {
          self.create(title: e[:title], url: e[:url])
          }
        end
      end
        main     = Thread.main       # The main thread
        current  = Thread.current    # The current thread
        all      = Thread.list       # All threads still running

        all.each { |t| t.join }
    end
4

1 回答 1

0

基本上,是的。您可能需要调用 config.threadsafe!在 application.rb 和 mayve allow_concurrency: true 在 database.yml 中。根据您的 rails 版本,您可能至少需要第一个,否则您的数据库请求可能不会并行运行。

尽管如此,在您的情况下,并行运行每个“INSERT INTO ...”可能没有太大的性能影响,认为这在很大程度上取决于您的磁盘、内存和数据库主机上的 CPU 情况。顺便说一句,如果您的 fetch_all_posts 需要相当长的时间来获取,您可以使用 find_each 方法,这可能会在扫描大量数据集的同时启动创建线程。您可以为 find_each 设置“页面”大小,使其在每 10 个帖子上运行一次广告。

于 2012-12-03T00:53:20.133 回答