python-rtmidi icon indicating copy to clipboard operation
python-rtmidi copied to clipboard

Is data conflict between MIDIIN thread and main function loop?

Open Hi-Music opened this issue 1 year ago • 1 comments

Thank you,SpotlightKid!Python-rtmidi is the best Python binding for RtMidi in the world! I am reading the midiclock.py in examples\advanced. I find that clock (MIDIClockReceiver instance) is shared between MIDIIN thread and main function loop. Can you tell me that Is there data conflict between MIDIIN thread and main function loop? I think that main loop and midiin should not write or read clock at the same time. Thank you very much!

def main(args=None):
    ap = argparse.ArgumentParser(usage=__doc__.splitlines()[0])
    ap.add_argument('-p', '--port', help="MIDI input port index / name.")
    ap.add_argument('bpm', type=int, default=120, help="Starting BPM.")
    args = ap.parse_args(args)
    clock = MIDIClockReceiver(args.bpm)
    try:
        m_in, port_name = open_midiinput(args.port)
    except (EOFError, KeyboardInterrupt):
        return 1
    
    #clock is shared between MIDIIN thread and main function loop.
    m_in.set_callback(clock)
    # Important: enable reception of MIDI Clock messages (status 0xF8)
    m_in.ignore_types(timing=False)

    try:
        print("Waiting for clock sync...")
        while True:
            time.sleep(1)

            if clock.running:
                if clock.sync:
                    print("%.2f bpm" % clock.bpm)
                else:
                    print("%.2f bpm (no sync)" % clock.bpm)

    except KeyboardInterrupt:
        pass
    finally:
        m_in.close_port()
        del m_in

Hi-Music avatar Jul 29 '24 13:07 Hi-Music

The main thread only reads the running and bpm attributes of the MIDIClockReceiver instance, it does not write them.

Yes, when the receiver thread sets the bpm attribute, the operation is not atomic, so the main thread might, see an outdated value when it happens to read it at the wrong time, but I don't think it matters much for this application. If you worry about that, put a lock around line 43f and test it before reading bpm. Or use a queue instead.

SpotlightKid avatar Aug 05 '24 03:08 SpotlightKid

Closing this due to the question being answered and no further feedback.

SpotlightKid avatar Feb 10 '25 17:02 SpotlightKid