J
James Mills
Hey all,
I have this concept I'm working on and here is
the code... Problem is if you run this it doesn't
terminate. I believe you can terminate it in the
main process by calling a.stop() But I can't find a
way for it to self terminate, ie: self.stop() As indicated
by the code...
----------------------------------------
#!/usr/bin/env python
import os
from time import sleep
from threading import Thread as _Thread
from multiprocessing import Process as _Process
class Process(object):
def __init__(self, *args, **kwargs):
super(Process, self).__init__(*args, **kwargs)
self.running = False
self.process = _Process(target=self._run)
def _run(self):
thread = _Thread(target=self.run)
thread.start()
try:
while self.running and thread.isAlive():
try:
sleep(1)
print "!"
except SystemExit:
self.running = False
break
except KeyboardInterrupt:
self.running = False
break
finally:
thread.join()
def start(self):
self.running = True
self.process.start()
def run(self):
pass
def stop(self):
print "%s: Stopping ..." % self
self.running = False
class A(Process):
def run(self):
while self.running:
sleep(5)
self.stop()
a = A()
a.start()
while a.running:
sleep(1)
print "."
print "DONE"
I have this concept I'm working on and here is
the code... Problem is if you run this it doesn't
terminate. I believe you can terminate it in the
main process by calling a.stop() But I can't find a
way for it to self terminate, ie: self.stop() As indicated
by the code...
----------------------------------------
#!/usr/bin/env python
import os
from time import sleep
from threading import Thread as _Thread
from multiprocessing import Process as _Process
class Process(object):
def __init__(self, *args, **kwargs):
super(Process, self).__init__(*args, **kwargs)
self.running = False
self.process = _Process(target=self._run)
def _run(self):
thread = _Thread(target=self.run)
thread.start()
try:
while self.running and thread.isAlive():
try:
sleep(1)
print "!"
except SystemExit:
self.running = False
break
except KeyboardInterrupt:
self.running = False
break
finally:
thread.join()
def start(self):
self.running = True
self.process.start()
def run(self):
pass
def stop(self):
print "%s: Stopping ..." % self
self.running = False
class A(Process):
def run(self):
while self.running:
sleep(5)
self.stop()
a = A()
a.start()
while a.running:
sleep(1)
print "."
print "DONE"