V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
xiaoyanbot
V2EX  ›  问与答

Python 的线程,没有调用 start 为什么也执行了? 请教下

  •  
  •   xiaoyanbot · Dec 10, 2022 · 1577 views
    This topic created in 1235 days ago, the information mentioned may be changed or developed.

    如下代码, 无论有没有 main ,使用 threading.Thread 没有 start , 为什么运行都执行了。

    Python 3.8+ , Win 和 Mac 表现都是在这个样子,请教下怎么回事,谢谢

    代码片段一 [有 main 的] :

    import time
    import threading
    
    
    def print_one():
        while True:
            print(time.time())
            time.sleep(2)
    
    
    if __name__ == '__main__':
        t1 = threading.Thread(target=print_one())
        # t1.start()
        print(threading.enumerate())
        
    

    代码片段二 [没有 main 的]

    import time
    import threading
    
    
    def print_one():
        while True:
            print(time.time())
            time.sleep(2)
    
    
    t1 = threading.Thread(target=print_one())
    # t1.start()
    print(threading.enumerate())
    
    
    3 replies    2022-12-10 20:30:49 +08:00
    stein42
        1
    stein42  
       Dec 10, 2022   ❤️ 1
    t1 = threading.Thread(target=print_one) # 去掉 print_one 后的括号
    xiaoyanbot
        2
    xiaoyanbot  
    OP
       Dec 10, 2022
    @stein42 感谢! 可以了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5846 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 03:08 · PVG 11:08 · LAX 20:08 · JFK 23:08
    ♥ Do have faith in what you're doing.