Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instrument connections not closed upon sysexit due to running Monitor thread #3814

Closed
nulinspiratie opened this issue Jan 11, 2022 · 2 comments

Comments

@nulinspiratie
Copy link
Contributor

The qcodes __init__.py file contains the following lines (116-120):

# ensure to close all instruments when interpreter is closed
import atexit
import logging

atexit.register(Instrument.close_all)

This is meant to ensure that all instrument connections are terminated once the interpreter closes.
However, if a non-daemon thread is initialized, the registered atexit functions are never called. This is a known issue, see e.g. https://stackoverflow.com/questions/58910372/script-stuck-on-exit-when-using-atexit-to-terminate-threads and https://stackoverflow.com/questions/3713360/python-2-6-x-theading-signals-atexit-fail-on-some-versions

One situation where this occurs is when a Monitor is started to show instrument parameters. Since it's not a daemon thread, no instrument connections are actually closed upon exiting the interpreter. This can cause issues such as not being able to connect to instruments the next try.

Steps to reproduce

A minimal example is the following:

def save_file():
    with open('output_file.txt', 'w') as outfile:
        outfile.write('Successfully terminated and called exit function')
        
import atexit
atexit.register(save_file)

import threading
threading.Thread(target=sleep, args=(60,))

If you exit the interpreter within 60 seconds of executing this code, the thread is still running and so the file output_file.txt is never created.

Proposed solution

A solution to this problem is making the Monitor a daemon thread. It should be ensured that this thread does realize when the interpreter is closed, in which case it should terminate itself.

@jenshnielsen
Copy link
Collaborator

@nulinspiratie Thanks for the detailed report. Making the monitor a daemon tread sounds reasonable and arguably more correct for the monitor.

#3774 is another suggestion for how the closing of each instrument more gracefully once it goes out of scope

@jenshnielsen
Copy link
Collaborator

#5565 made the monitor a daemon thread so closing this one

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

No branches or pull requests

2 participants