【问题标题】:Python Threads collectionPython 线程集合
【发布时间】:2016-12-11 12:02:49
【问题描述】:

我有一个类似这样的代码,

import threading

class Mythread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
        def run(self):
            print('do some processing')

if __name__=='__main__':
       while Ture:
         val = raw_input('next thread')
         t = MyThread()
         t.start()
         t.join()

问题是我怎样才能在不阻塞主函数的情况下继续主函数,因为t.join() 停止主函数直到 t 没有完成?

【问题讨论】:

    标签: multithreading python-3.x return python-multithreading


    【解决方案1】:

    您应该将代码放在“代码”标签中,否则它不是真正可读的。 而你只需要这样做。

    if name == 'main':
        #Thread creation
        allThreads = []
        while True:
            val = raw_input('next thread')
            newThread = MyThread()
            newThread.start()
            allThreads.append(newThread)
    
        #You can do something here
    
        #Waiting for all threads to stop
        for thread in allThreads: 
            thread.join()
    

    【讨论】:

    • 谢谢,主程序总是停留在while循环中,怎么会去#Waiting for all threads to stop??我希望 while 循环(在 main 中)永远存在,并且需要收集线程以停止。在while循环中。
    • 其实我想要的,只是想启动线程,又不想让它回到main。因此,当该线程中的任务完成时,它会释放该线程。
    猜你喜欢
    • 2011-12-14
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2015-01-16
    相关资源
    最近更新 更多