defmain(): print(f"starting at :{ctime()}") threads = [] for i inrange(len(loops)): t = thread.Thread(target=loop, args=(i, loops[i])) t.daemon = True threads.append(t)
for i inrange(len(loops)): threads[i].start()
for i inrange(len(loops)): threads[i].join() print("all done")
main()
类形式创建
import threading as thread from time import sleep, ctime
defmain(): print(f"starting at :{ctime()}") threads = [] for i inrange(len(loops)): t = thread.Thread(target=MyThread(loop,(i,loops[i]),loop.__name__)) t.daemon = True threads.append(t)
for i inrange(len(loops)): threads[i].start()
for i inrange(len(loops)): threads[i].join() print("all done")
main()
子类形式创建
import threading as thread from time import sleep, ctime
loops = [3,2]
classMyThread(thread.Thread): def__init__(self, func, args, name=''): thread.Thread.__init__(self) #Changed: need to inherit and call parent's init self.func = func self.args = args self.name = name
defmain(): threads = [] for i inrange(len(loops)): t = MyThread(loop, (i, loops[i]), loop.__name__+str(i)) #Changed:no need to use threading.Thread() method t.daemon = True threads.append(t)
for i inrange(len(loops)): threads[i].start()
for i inrange(len(loops)): threads[i].join() print("all done")
main()
实例:
#my_thread.py import threading as thread from time import ctime
classMyThread(thread.Thread): def__init__(self, func, args, name=''): thread.Thread.__init__(self) # Changed: need to inherit and call parent's init self.func = func self.args = args self.name = name
#main.py from my_thread import MyThread from time import ctime, sleep
deffib(x): sleep(0.002) if x < 2: return1 return fib(x-2) + fib(x-1)
deffac(x): sleep(0.1) if x < 2: return1 return x * fac(x-1)
defsum(x): sleep(0.2) if x < 2: return1 return x + sum(x-1)
funcs = [fib, fac, sum] n = 12
defmain(): print("****** Single THREAD ********") for i inrange(len(funcs)): print("start function %s" % funcs[i].__name__) print(funcs[i](n)) print("end function %s" % funcs[i].__name__)
threads = [] print("****** Multi THREAD ********") for i inrange(len(funcs)): t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t)
for i inrange(len(funcs)): threads[i].start()
for i inrange(len(funcs)): threads[i].join() print(threads[i].get_result())