commoccoom
V2EX  ›  问与答

请教一个 Python 问题

  •  
  •   commoccoom · Dec 4, 2020 · 1578 views
    This topic created in 2165 days ago, the information mentioned may be changed or developed.
    import threading
    
    def f(dicts):
    	for key in dicts:
    		print (key,dicts[key])
    		
    dict1 = {'a':'b','c':'d'}
    
    ta = threading.Thread(target=f,kwargs=dict1)
    
    ta.start()
    

    为什么这里的f函数内无法使用for循环呢?

    6 replies  •  2020-12-04 14:23:08 +08:00
    sean10
    sean10
    Dec 4, 2020 via Android
    1
    加个 ta.join()吧,应该是你主进程结束把还没打印的子进程干掉了
    sean10
    sean10
    Dec 4, 2020 via Android
    2
    子线程
    Sylv
    Sylv
    Dec 4, 2020❤️1
    3
    写法 1:
    ta = threading.Thread(target=f, args=(dict1,))

    写法 2:
    ta = threading.Thread(target=f, kwargs={'dicts': dict1})

    了解下 args / kwargs / 解包等概念。
    commoccoom
    commoccoom
    OP
    Dec 4, 2020
    4
    @Sylv 可以了,非常感谢啊😁
    sean10
    sean10
    Dec 4, 2020 via Android
    5
    翻了下,我刚才说的错了,无关项
    commoccoom
    commoccoom
    OP
    Dec 4, 2020
    6
    @sean10 已经用 3L 的方法解决了啊😁
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   516 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 20:07 · PVG 04:07 · LAX 12:07 · JFK 15:07
    ♥ Do have faith in what you're doing.