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()
  • 相关阅读:
    架构-缓存
    工具-Memcahce和Redis比较
    职业-把工作当作职业 or 事业?
    MySQL-查询结果缓存
    MySQL-SQL语句中SELECT语句的执行顺序
    getXXXPos()约定
    FBX BlendShape/Morph动画解析
    quick cocos2dx 3.x 配置win32工程
    cocos2dx 3.x fullPathForFilename及isFileExist在ios/mac下与win32下行为不同
    osX显示隐藏文件
  • 原文地址:https://www.cnblogs.com/xiyuan2016/p/7123157.html
Copyright © 2011-2022 走看看