简体   繁体   English

Python线程-有什么区别?

[英]Python threading - what's the difference?

Could anyone explain why this code prints nothing: 任何人都可以解释为什么此代码不输出任何内容:

import threading

def threadCode1(): 
    while True:
        pass      

def threadCode2():
    while True:
        pass


thread = threading.Thread(target=threadCode1())
thread2 = threading.Thread(target=threadCode2())
thread.start()
print('test')
thread2.start()

But if I remove the brackets: 但是,如果我除去括号:

thread = threading.Thread(target=threadCode1)
thread2 = threading.Thread(target=threadCode2)

It does print 'test'? 它会打印“测试”吗? That's quite a surprising result for me. 对我来说,这是一个令人惊讶的结果。

Because, when you first evaluate the line with the thread call: 因为,当您第一次评估带有线程调用的行时:

thread = threading.Thread(target=threadCode1())

The first thing that line does is execute threadCode1() which makes the program jump to the threadCode1 function body, which is an infinite loop and the execution will never make it out of the function and execute the next lines in the main procedure. 该行要做的第一件事是执行threadCode1() ,它使程序跳转到threadCode1函数体,这是一个无限循环,执行将永远不会使其脱离函数并执行主过程中的下一行。

If you change threadCode1 to this: 如果将threadCode1更改为此:

def threadCode1(): 
    while True:
        print 'threadCode1'

You'll notice how it endlessly loops printing threadCode1 . 您会注意到它如何无限循环地循环打印threadCode1

When you start the threads, they run under a separate thread of control than your program. 当您启动线程时,它们在程序之外的单独控制线程下运行。 That means they are doing their own thing (looping forever) and your main process can continue doing what it wants. 这意味着他们正在做自己的事情(永远循环),并且您的主要过程可以继续做自己想要的事情。 As noted above, appending parens in the first example actually calls the function within the main process . 如上所述,在第一个示例中附加括号实际上是在main进程内调用该函数。 If you instead type 如果您改为输入

thread = threading.Thread(target=threadCode1)
thread2 = threading.Thread(target=threadCode2)
thread.start()
thread.join()
print('test')

You will experience what you expect to happen, since the main process is then waiting for the thread to finish. 您将体验到预期的结果,因为主要过程随后正在等待线程完成。

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

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