rubymultithreadingwatir

executing in another thread|RuntimeError


I have something similar in my project

class Raj
  def execute
    5.times do
      Thread.new do
        object = Gopal.new
        object.db_connection
        object.enter_tax_id
      end
    end
  end
end

class Gopal
  def db_connection
    @db = "" # Created db connection here
    @browser = Watir::Browser.new
  end

  def enter_tax_id
    m = Mutex.new
    m.synchronize do
      data = @db_conn.select_one("select max(tax_id_no) from pcmp.tax_identifier")
      @browser.text_field(id: 'something').set 'data'
    end
  end
end

The enter tax id method pulls information from the database and then enters a value into the text field. This thread has an issue since other threads are interacting with it; when multiple threads attempt to execute the same procedure, a 'executing in another thread' error is raised.


Solution

  • In order to resolve this issue, I used the following strategy:

    class Gopal
      @mutex = Mutex.new
      def self.mutex_var
        @mutex
      end
      def db_connection
        @db = "" # Created db connection here
        @browser = Watir::Browser.new
      end
    
      def enter_tax_id
        Gopal.mutex_var.synchronize do
          data = @db.select_one("select max(tax_id)+1 from table")
          @browser.text_field(id: 'something').set 'data'
        end
      end
    end
    

    The mutex variable is now persistent as long as the class is loaded, thus even if another object is instantiated, the mutex variable will still be present and provide protection.