我正在尝试使用python线程模块。因为我是系统管理员,所以在开发的时候会有一点困难;这个概念对我来说是新的。当主线程将标志设置为False
时,我启动两个线程并想要停止它们:
class My_Thread( threading.Thread):
def __init__(self, thread_id, thread_name, count):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.thread_name = thread_name
self.count = count
def run(self):
do_job(self.thread_name, self.thread_id, self.count)
def do_job(t_name, t_id, count):
while not get_kill():
print "It is "+str(time.time())+" and I am "+str(t_name)
print get_kill()
time.sleep(count)
kill = False
def get_kill():
return kill
def set_kill(state):
kill = state
if __name__ == '__main__':
a = My_Thread(1, "Thread-1", 2)
b = My_Thread(2, "Thread-2", 1)
a.start()
b.start()
while(True):
try:
pass
except KeyboardInterrupt,ki:
set_kill(True)
sys.exit(0)
但是两个线程中的值都不会被读取为已更改,并且它们不会退出。为什么这个值不能从线程中正确读取?你知道吗
问题
在
set_kill()
中,创建一个新的局部变量kill
,将其设置为state
,并从函数返回。实际上,您并没有在全局范围内更新kill
的值。你知道吗为此,您需要:
更好的方法
使用这样的全局变量通常被认为是不好的做法,您可能希望将
kill
变量和函数转换为一个对象,以便将数据和行为封装在一起:您可以这样使用:
相关问题 更多 >
编程相关推荐