zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    poj1014 Dividing (多重背包)
    HDOJ 1316 How Many Fibs?
    最大字串和
    WHY IE AGAIN?
    Codeforces Round #143 (Div. 2) (ABCD 思维场)
    自用组帧工具
    菜鸟学EJB(二)——在同一个SessionBean中使用@Remote和@Local
    shell 块注释
    检测到在集成的托管管道模式下不适用的 ASP.NET 设置的解决方法
    Windows Myeclipse 10 安装 Perl 插件
  • 原文地址:https://www.cnblogs.com/xiyuan2016/p/7123157.html
Copyright © 2011-2022 走看看