繁体   English   中英

当它们需要 arguments 时,我不能同时运行两个线程

[英]I can't run two threads at once when they require arguments

当我运行一些简单的东西时;

import threading,time,os

pathToFile = # some file

def play(self):
    os.system("cvlc " + self)

def dummyAction():
    while True:
        print('working')
        time.sleep(1)


threading.Thread(target = dummyAction).start()
threading.Thread(target = play(pathToFile)).start()

我可以同时运行play()dummyAction()
但是如果我给dummyAction()一个参数,它就不会运行play()

pathToFile = # some file

def play(self):
    os.system("cvlc " + self)

def dummyAction(self):
    while True:
        print(self)
        time.sleep(1)


threading.Thread(target = dummyAction('Working')).start()
threading.Thread(target = play(pathToFile).start()

我只剩下dummyAction自己运行了。


我需要能够同时使用 arguments 运行两个函数。
我怎样才能让它工作?


运行: Raspberry Pi OS(32 位)/2021-01-11 (Linux)

要修复,请为Thread使用args参数:

threading.Thread(target=dummyAction, args=('Working',)).start()
threading.Thread(target=play, args=(pathToFile,)).start()

在您的第一个示例中,这是不正确的:

threading.Thread(target = play(pathToFile)).start()

因为它实际上调用了 function play(pathToFile)并在创建和启动线程之前将其返回值设置为target 因此,它似乎有效只是巧合。 实际上dummyAction() function 会在新线程中执行,但play() function 实际上是在主线程中执行的。

这就解释了为什么您的第二个示例没有启动第二个线程; 程序被阻止运行dummyAction()

这就是您应该将 arguments 传递给线程的方式:

threading.Thread(target=dummyAction, args=('Working',)).start()
threading.Thread(target=play, args=(pathToFile,)).start()

暂无
暂无

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

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