Karim
Karim

Reputation: 1313

Why are do instance variables not work in new threads

I am new to diving into the world of multi-threading and am trying to build a motion detector that opens on another thread (so that I can keep working on my main thread).

def start_motion_detector
        # Create a new thread so that processes can run concurrently
        @thread = Thread.new do     

            # Connect to Arduino
            arduino = ArduinoFirmata.connect

            # Declare Pin 7 on the Arduino as an input pin
            arduino.pin_mode 7, ArduinoFirmata::INPUT

            # light = LifxInterface.new

            # Read the digital pins
            arduino.on :digital_read do |pin, status|
                # What to do if there is motion
                if pin == 7 && status == true
                    # light.turn_on
                    arduino.digital_write 13, true
                end

                # What to do if there is no motion
                if pin == 7 && status == false
                    # light.turn_off
                    arduino.digital_write 13, false
                end
            end
        end
    end

The issue that I'm having is that this code works perfectly when I leave "arduino" as a local variable inside my new thread. However, as soon as I put an @ in front of it, the motion detector stops working completely. The reason I want to make this an instance variable is that I'd like to pull out the configuration steps (connecting to the Arduino and setting the input pin) into an initialize method. Why is this happening?

Upvotes: 0

Views: 88

Answers (1)

user2619418
user2619418

Reputation:

Instance variables do work in new threads.

I just tested your code (simplified version) and it works as a charm. You have another problem. Maybe you haven't replaced all the @ or maybe you are using @arduino elsewhere and it's not thread safe.

def start_motion_detector
  @var = "hey"
  # Create a new thread so that processes can run concurrently
  @thread = Thread.new do
    puts @var
  end
end


start_motion_detector
gets.chomp

If the previous code fails to you, please tell me the Ruby version and the modified code.

Upvotes: 1

Related Questions