I’m writing a program which reads and writes from and to the serial port. There are two threads; one thread reads and writes from/to the serial port every 500ms, and the other thread writes to the serial port every 3s.
The issue I’m having is, since 500ms is a multiple of 3s, at 3s, 6s, 9s… the 500ms loop fails to read/write from/to the serial port. Is there are way to check whether the serial port is in use?
counter = 0
switchRelays = DoEvery([3], 20) do
sp.write "@00 WR #{relays[counter]}\r"
counter = (counter + 1) % relays.length
end
# This thread samples every 500ms.
sp.write "@00 AI 0\r"
sleep 0.2
sample500 = DoEvery([0.5], 1.0/0.0) do |timeStamp|
if switchRelays.alive? == false
csv.close
puts 'Done'
sample500.exit
else
sleep 0.1
analogueStatus = sp.readline
sp.write "@00 AI 0\r"
end
end
This is a classic example of a shared object where you need to synchronize concurrent access attempts.
You can use Mutex, for example.