I need to close the connection, but due to the instability of the OPC server, the close method is “hung up”.

I need some kind of either interruption or continuation of the thread execution.

I looked at the ability to implement using threading , but the suspicion crept in that the calling thread will not be closed until the run method is executed.

How to change this implementation so as not to create a memory leak?

 import threading import OpenOPC class Worker(threading.Thread): def __init__(self, func): threading.Thread.__init__(self) self.daemon = True self.func = func def run(self): self.func.close() def test(): t = Worker(OpenOPC.connect('localhost')) t.start() t.join(5) return 
  • Please reformulate the question so that it is not a “classical questionnaire”. - aleksandr barakin

1 answer 1

Taking into account the fact that it is not good to “kill” a stream, so I decided to review the possibility of closing the connection in a separate process.

After waiting for the required time, the process is simply destroyed. This option suits me because I do not need to keep track of what will happen in the process.

 from multiprocessing import Process import time import OpenOPC def break_con(conn): func = OpenOPC.open_client('localhost') proc = Process(target=func.close) proc.start() time.sleep(10) proc.terminate() 
  • one
    In order not to wait 10 seconds, if the process was completed earlier, you can proc.join(10); if proc.is_alive(): proc.terminate() proc.join(10); if proc.is_alive(): proc.terminate() use. Here join() may return earlier than 10 seconds. - jfs