Python模块学习------ 多线程threading(1)

# Method 1: 创建一个Thread实例,传给它一个函数;

import threading
from time import sleep, ctime loops = [4,2] def loop(nloop, nsec):
print "start loop", nloop, "at:",ctime()
sleep(nsec)
print "end loop", nloop, "at:",ctime() def main():
print "*****start*********", ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=loop, args=(i, loops[i]))
threads.append(t) # start threads
for i in nloops:
threads[i].start() # wait for all threads to finish
for i in nloops:
threads[i].join() print "*******end*******", ctime() if __name__ == "__main__":
main()
# Method 2: 创建一个Thread的实例,传给它一个可调用的类对象
import threading
from time import sleep, ctime loops = [4,2] class ThreadFunc(object): def __init__(self, func, args, name =''):
self.name = name
self.func = func
self.args = args def __call__(self):
apply(self.func, self.args) def loop(nloop, nsec):
print "start loop", nloop, "at:",ctime()
sleep(nsec)
print "end loop", nloop, "at:",ctime() def main():
print "*****start*********", ctime()
threads = []
nloops = range(len(loops)) # create all threads
for i in nloops:
t = threading.Thread(target=ThreadFunc(loop, (i,loops[i]), loop.__name__))
threads.append(t) # start all threads
for i in nloops:
threads[i].start() # wait for all threads to finish
for i in nloops:
threads[i].join() # join() 程序挂起,直至线程结束 print "*******end*******", ctime() if __name__ == "__main__":
main()
上一篇:python语法_字符编码


下一篇:2假动作,数据缓冲,CCEaseExponential,CCEaseElastic,CCEaseBounce,CCCallFunc,funcNCallBack,funcNDCallBack,funcO