我有一个脚本,我想让一个函数与另一个函数同时运行。
我看过的示例代码如下:
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'
发布于 2010-05-25 23:20:57
你不需要使用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")
在这里,我展示了如何使用线程模块来创建一个调用普通函数作为其目标的线程。您可以看到我如何在线程构造函数中向它传递所需的任何参数。
发布于 2015-07-08 15:18:12
我尝试添加另一个join(),它似乎起作用了。以下是代码
from threading import Thread
from time import sleep
def function01(arg,name):
for i in range(arg):
print(name,'i---->',i,'\n')
print (name,"arg---->",arg,'\n')
sleep(1)
def test01():
thread1 = Thread(target = function01, args = (10,'thread1', ))
thread1.start()
thread2 = Thread(target = function01, args = (10,'thread2', ))
thread2.start()
thread1.join()
thread2.join()
print ("thread finished...exiting")
test01()
发布于 2010-05-25 23:18:33
您是否覆盖了run()方法?如果您重写了__init__
,您是否确保调用了基本threading.Thread.__init__()
在启动两个线程后,主线程是否继续在子线程上无限期地工作/阻塞/联接,以便在子线程完成任务之前主线程的执行不会结束?
最后,您是否得到了任何未处理的异常?
https://stackoverflow.com/questions/2905965
复制相似问题