Does concurrency happen even when only one thread is in a thread pool?

前端 未结 3 1129
失恋的感觉
失恋的感觉 2021-02-05 10:46

I\'m using Rails 5 and Ruby 2.4. How can I figure out, or can you tell by looking at the below, whether there are multiple threads running at the same time?

poo         


        
3条回答
  •  无人及你
    2021-02-05 11:35

    You assumption that there is only one thread is incorrect. There are two - the one in the thread pool and the main one that spawned the one in the thread pool.

    You might be confused as you made the main thread wait and it shouldn't access the database. That doesn't mean that it still doesn't hold a connection, hence preventing the other thread from acquiring one.

    As a rule of thumb your database connection pool should be set to at least number of threads spawned + 1. In this case - 2.


    Code to easily reproduce:

    # migration
    class CreateFoos < ActiveRecord::Migration[5.0]
      def change
        create_table :foos do |t|
          t.integer :bar
        end
      end
    end
    
    # model
    class Foo < ApplicationRecord
    end
    
    # rake task
    task experiment: :environment do
      Foo.create
      pool = Concurrent::FixedThreadPool.new(1) 
      promise = 
        Concurrent::Promise.execute(executor: pool) do
          Foo.first.update_attributes!(bar: rand(-42..42))
        end
      promise.wait.value!
    end
    

    Set pool to 1 in your config/database.yml and run the task. You will get an error. Set it to 2 - it will be just fine.

    You can increase the number of threads in the pool and add at least that much promises for processing. You will consistently fail for database connection pool = number of threads in the thread pool and succeed if you add one more in config/database.yml.

提交回复
热议问题