You should add a lock in the write function, to avoid thread collisions between the heartbeat and user issued commands.