我有一个脚本,我希望一个函数与另一个函数同时运行。
我看过的示例代码:
import threading
def MyThread (threading.thread):
# doing something........
def MyThread2 (threading.thread):
# doing something........
MyThread().start()
MyThread2().start()
我无法正常工作。我更愿意使用线程函数而不是类来实现这一点。
这是工作脚本:
from threading import Thread
class myClass():
def help(self):
os.system('./ssh.py')
def nope(self):
a = [1,2,3,4,5,6,67,78]
for i in a:
print i
sleep(1)
if __name__ == "__main__":
Yep = myClass()
thread = Thread(target = Yep.help)
thread2 = Thread(target = Yep.nope)
thread.start()
thread2.start()
thread.join()
print 'Finished'
最佳答案
您不需要使用 Thread
的子类来完成这项工作 - 请查看我在下面发布的简单示例,了解如何操作:
from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
这里我展示了如何使用线程模块来创建一个调用普通函数作为其目标的线程。你可以看到我如何在线程构造函数中传递我需要的任何参数。
https://stackoverflow.com/questions/2905965/