调用之间线程持久性
我找不到办法让我的线程在第一次和第二次调用脚本之间保持持续运行。
到目前为止,当我运行 python script_1.py A
时,脚本会执行 if option == 'A'
这部分代码并启动一个线程。然后,脚本结束,线程也被清理掉了。所以,当我运行 python script_1.py B
时,isAlive
这个属性就不能用了。
有没有什么办法可以保持持续性呢?
script_1.py 的代码是:
from script_2 import imp
script_2 = imp()
if option == 'A':
script_2.start()
elif option == 'B':
script_2.stop()
而 script_2.py 的代码是:
from threading import Thread
class workerThread(Thread):
def __init__(self, _parent):
Thread.__init__(self)
self.parent = _parent
self.active = False
def run(self):
while(self.active == False):
print 'I am here'
print 'and now I am here'
class imp():
def __init__(self):
self.threadObj = None
def start(self):
self.threadObj = workerThread(self)
self.threadObj.start()
def stop(self):
if self.threadObj.isAlive() == True:
print 'it is alive'
1 个回答
0
一个解决方案是:
from threading import Thread
from socket import *
from time import sleep
class workerThread(Thread):
def __init__(self):
Thread.__init__(self)
self.sock = socket()
self.sock.bind(('', 9866))
self.sock.listen(4)
self.start()
def run(self):
while 1:
ns, na = self.sock.accept()
if ns.recv(8192) in (b'quit', 'quit'):
ns.close()
break
self.sock.close()
print('Worker died')
imp = workerThread()
还有第一个脚本:
if option == 'A':
from time import sleep
from script_2 import imp
while 1:
sleep(0.1)
elif option == 'B':
from socket import *
s = socket()
s.connect(('127.0.0.1', 9866))
s.send('quit') # b'quit' if you're using Python3
s.close()
这段代码看起来并不优雅,但它只是一个5分钟内做出来的简单示例,给你一个大概念。
为了让这段代码更接近实际可用,我会这样做:
self.sock = fromfd('/path/to/socket', AF_UNIX, SOCK_DGRAM)
并在工作线程中用一个ePoll对象来注册它。
import select
self.watch = select.epoll()
self.watch.register(self.sock.fileno(), select.EPOLLIN)
while 1:
for fd, event in self.watch.poll(0.1):
if fd == self.sock.fileno() and event == select.EPOLLIN:
ns, na = self.sock.accept()
# store socket and register it
elif event == select.EPOLLIN:
data = storedSockets[fd].recv(8192)
# and do work on it
总之,你需要保持第一次执行的实例在运行,并为你启动的第二个实例创建某种通信方式。我用套接字作为例子,我觉得这个方法挺不错的,特别是结合Unix套接字和epoll,因为速度非常快。你也可以使用memcache。