Skip to content

fix: stop Arduino communicator thread before closing serial port - #19

Open
alexevag wants to merge 1 commit into
mainfrom
fix/arduino-serial-thread-shutdown
Open

alexevag wants to merge 1 commit into
mainfrom
fix/arduino-serial-thread-shutdown

Conversation

@alexevag

Copy link
Copy Markdown
Collaborator

Fix Arduino serial shutdown race

Arduino.cleanup() closed the serial port while the background communicator thread was still running, so the thread could hit a closed port mid-read and raise on exit.

Changes

  • cleanup() now signals thread_end, joins the communicator thread with a 2 second timeout, and only then closes the serial connection. A warning is logged if the thread does not stop in time.
  • The communicator thread is started as a daemon, so a stuck thread cannot block interpreter shutdown.
  • thread_end and msg_queue moved from class attributes to instance attributes in __init__. As class attributes they were shared across every Arduino instance, meaning one instance's cleanup would stop another's thread.
  • Dropped the callbacks = True class attribute, which shadowed the value the base Interface already sets from its constructor argument.

Files

  • src/ethopy/interfaces/Arduino.py

The _communicator thread was never signalled to stop, so cleanup() closed the serial port while the thread kept polling ser.in_waiting on the dead file descriptor, raising OSError: [Errno 9] Bad file descriptor.

cleanup() now sets thread_end and joins the thread before ser.close().

Also move thread_end and msg_queue from class attributes to instance attributes: as class attributes they were shared process-wide, so a second Arduino instance would inherit an already-set thread_end and its communicator would exit immediately. The class-level callbacks=True was dead code, always shadowed by the instance attribute set in Interface.__init__.

The communicator thread is now a daemon, so if a wedged readline() ever makes the join time out, the leftover thread cannot block interpreter shutdown.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant