简体   繁体   English

使用python进行多线程

[英]multithreading using python

Trying to understand the following results when using multithreading with python. 与python一起使用多线程时,尝试了解以下结果。 The following code prints A and B to the console in random sequence, which is what I would like to achieve. 以下代码以随机顺序将A和B打印到控制台,这是我想要实现的。 But the second piece of code only prints "A" to the console, and never proceeds past t1.start(). 但是第二段代码仅在控制台上显示“ A”,并且永远不会经过t1.start()。 Why is this? 为什么是这样? What do I need to do the the second section of code to make it behave like the first? 我需要执行第二部分代码以使其表现得像第一部分一样吗?

Thanks in advance, this is my first post. 预先感谢,这是我的第一篇文章。

This is the behavior I want : 这是我想要的行为:

from threading import Thread
def runA():
    while True:
        print ('A\n')

def runB():
    while True:
        print ('B\n')

if __name__ == "__main__":
     t1 = Thread(target = runA())
     t2 = Thread(target = runB())
     t1.setDaemon(True)
     t2.setDaemon(True)
     t1.start()
     t2.start()
     while True:
         pass

I want the behavior produced from the above code but using classes like in the example below. 我想要从上面的代码产生的行为,但是要使用下面示例中的类。 The code below never executes t2.start(). 以下代码从不执行t2.start()。 Why is this? 为什么是这样?

from threading import Thread
class test():
     def runA(self):
         while True:
             print ('A\n')

     def runB(self):
         while True:
             print ('B\n')

if __name__ == "__main__":
     testingNow=test()
     t1 = Thread(target = testingNow.runA())
     t2 = Thread(target = testingNow.runB())
     t1.setDaemon(True)
     t2.setDaemon(True)
     t1.start()
     t2.start()
     while True:
         pass

摆脱()testingNow.runA()testingNow.runB()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM