在python中创建线程
发布于 2021-01-29 17:06:35
我有一个脚本,我希望一个函数与另一个函数同时运行。
我看过的示例代码:
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'
关注者
0
被浏览
42
1 个回答
-
您无需使用的子类
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")
在这里,我展示了如何使用线程模块创建一个线程,该线程调用普通函数作为其目标。您可以看到如何在线程构造函数中将所需的任何参数传递给它。