python3多线程模块_Python3,多线程处理在每个线程完成时将数据输入主模块

更新:

好的,所以您想知道更多关于如何让display1.py打印结果的信息。如果你能解释为什么这很重要,那会很有帮助,因为这可能会改变你应该怎么做,但这里有一个第一种方法:# threads1.py

from threading import Thread

import time

class ThreadManager:

def __init__(self):

self.threads = {}

def start(self):

t1 = MyThread(4)

t1.daemon = True

t1.start()

self.threads[1] = t1

t2 = MyThread(1)

t2.daemon = True

t2.start()

self.threads[2] = t2

def is_alive(self, thread_id):

return self.threads[thread_id].is_alive()

def GetResults(self): # or you could just access results directly

return self.results

class MyThread(Thread):

def __init__(self, SleepWait):

Thread.__init__(self)

self.SleepWait = SleepWait

def run(self):

time.sleep(self.SleepWait)

然后。。。在

^{pr2}$

您最终应该考虑使用Crast建议的队列;但是让我们先关注一下如何正确使用它。在

原帖:

此代码存在许多问题。在

首先,应该使用t1.is_alive()检查线程是否完成。不需要用AskFinished重新实现它。在

第二,threads1.py中的while True:循环在等待线程终止时以的速度不做任何事情。如果你不相信我的话,看看这个运行时的cpu使用情况。您应该在那里抛出一个time.sleep(1)语句。在

第三,为什么要使用全局var来返回结果?这真是件奇怪的事。把它存起来就行了!在

最后,为什么display1.py必须打印消息?为什么thread1.py不能这样做?在

考虑到这四点,这里有一个thread1.py,它的作用更为合理:from threading import Thread

import time

class ThreadManager:

def __init__(self):

self.results = None

def start(self, answer): # why is "answer" here?

self.answer = answer

thread_refs = []

t1 = MyThread(4, 'Not finished')

t1.daemon = True

t1.start()

t2 = MyThread(1, 'Not finished')

t2.daemon = True

t2.start()

t1_state = t2_state = True

while t1.is_alive() or t2.is_alive():

time.sleep(1)

if t1.is_alive() != t1_state:

print("t1 finished")

t1_state = t1.is_alive()

if t2.is_alive() != t2_state:

print("t2 finished")

t2_state = t2.is_alive()

if not t1.is_alive() and not t2.is_alive():

self.results = [t1.AskFinished, t2.AskFinished]

print("Both Finished")

break

def GetResults(self): # or you could just access results directly

return self.results

class MyThread(Thread):

def __init__(self, SleepWait, AskFinished):

Thread.__init__(self)

self.SleepWait = SleepWait

self.AskFinished = AskFinished

def run(self):

time.sleep(self.SleepWait)

self.AskFinished = 'Finished'

现在,这仍然不能完全满足您的需要,因为您要求display.py来显示。要实现这一点,您必须将while True循环放入display.py,并添加一个ThreadManager.is_alive()方法,display.py可以用来检查线程是否处于活动状态。如果你想知道怎么做,让我知道。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值