How to interrupt streams in Twisted?

I am having a problem with the following code. In my real situation, the logic enclosed in SomeClass has blocking logic, so I need to call it using reactor.callFromThread() . I want the loop in SomeClass.run () to stop when I give a signal, and I understand that for this, some code must be executed in the addSystemEvent addon. I think this may be more of a problem with my understanding of Python and streaming than with Twisted itself.

 from twisted.internet import reactor import time class SomeClass(): def __init__(self): self.running = False def run(self): self.running = True while(self.running): print('foo') time.sleep(5) def stop(self): print('stopping') self.running = False someClassInstance = SomeClass() def cleanup(): someClassInstance.stop() reactor.addSystemEventTrigger('before', 'shutdown', cleanup) reactor.callFromThread(someClassInstance.run) reactor.run() 
+4
source share
1 answer

It is not possible to safely and generally interrupt a thread in a programming language such as Python. Java used this function, but they removed it because it is inherently unsafe. (Java has a new Thread.interrupt function, which is a limited version with fewer problems, but still complicates the task of writing multi-threaded code).

This is why Twisted provides many ways to avoid threads. If they do not need you, do not use them. For example, instead of calling time.sleep(n); foo() time.sleep(n); foo() just execute reactor.callLater(n, foo) and you will get the same effect, except that callLater returns an object that you can use to easily cancel or defer foo if it hasn't already happened.

If you have an example of what you are actually trying to do, rather than replacing โ€œ time.sleep โ€ with โ€œand then something happensโ€, please open another question explaining it. The answer really depends on what you do - do you really expect on time? Blocking I / O to another process? Another car? Twisted has the appropriate capabilities for all of these.

+4
source

Source: https://habr.com/ru/post/1400137/


All Articles