• 【python】多线程


         科技在发展,时代在进步,我们的CPU也越来越快,CPU抱怨,P大点事儿占了我一定的时间,其实我同时干多个活都没问题的;于是,操作系统就进入了多任务时代。我们听着音乐吃着火锅的不在是梦想。python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费你和时间,所以我们直接学习threading 就可以了。

    继续对上面的例子进行改造,引入threadring来同时播放音乐和视频:

    #coding=utf-8
    import threading
    from time import ctime,sleep
    
    
    def music(func):
        for i in range(2):
            print "I was listening to %s. %s" %(func,ctime())
            sleep(1)
    
    def move(func):
        for i in range(2):
            print "I was at the %s! %s" %(func,ctime())
            sleep(5)
    
    threads = []
    t1 = threading.Thread(target=music,args=(u'爱情买卖',))
    threads.append(t1)
    t2 = threading.Thread(target=move,args=(u'阿凡达',))
    threads.append(t2)
    
    if __name__ == '__main__':
        for t in threads:
            t.setDaemon(True)
            t.start()
    
        print "all over %s" %ctime()
    

      

    import threading

    首先导入threading 模块,这是使用多线程的前提。

     

    threads = []

    t1 = threading.Thread(target=music,args=(u'爱情买卖',))

    threads.append(t1)

      创建了threads数组,创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。

      接着以同样的方式创建线程t2,并把t2也装到threads数组。

     

    for t in threads:

      t.setDaemon(True)

      t.start()

    最后通过for循环遍历数组。(数组被装载了t1和t2两个线程)

     

    setDaemon()

      setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。

     

    start()

    开始线程活动。

     

    运行结果:

    >>> ========================= RESTART ================================
    >>> 
    I was listening to 爱情买卖. Thu Apr 17 12:51:45 2014 I was at the 阿凡达! Thu Apr 17 12:51:45 2014  all over Thu Apr 17 12:51:45 2014

      从执行结果来看,子线程(muisc 、move )和主线程(print "all over %s" %ctime())都是同一时间启动,但由于主线程执行完结束,所以导致子线程也终止。

     

    另外一个小实例:

    #!/usr/bin/env python
    
    import threading
    from time import sleep, ctime
    
    loops = [ 4, 2 ]
    
    def loop(nloop, nsec):
        print 'start loop', nloop, 'at:', ctime()
        sleep(nsec)
        print 'loop', nloop, 'done at:', ctime()
    
    def main():
        print 'starting at:', ctime()
        threads = []
        nloops = range(len(loops))
    
        for i in nloops:
            t = threading.Thread(target=loop,
    	    args=(i, loops[i]))
            threads.append(t)
    
        for i in nloops: # start threads
            threads[i].setDaemon(True)
            threads[i].start()
    
        for i in nloops:            # wait for all
            threads[i].join()       # threads to finish
    
        print 'all DONE at:', ctime()
    
    if __name__ == '__main__':
        main()
    

      

  • 相关阅读:
    ie6的兼容性问题?
    localstorage,sessionstorage,cookie的比较?
    vuex与localstorage的比较?
    当数据量大时的加载原理?
    input控件的兼容性问题?
    京东数科Java实习面试(offer到手含面试经验及答案)
    车好多Java实习面试(offer到手含面试经验及答案)
    小屋信息Java实习面试(offer到手含面试经验及答案)
    比特大陆Java实习面试(offer到手含面试经验及答案)
    微众银行Java实习面试(offer到手含面试经验及答案)
  • 原文地址:https://www.cnblogs.com/paulwinflo/p/5019389.html
Copyright © 2020-2023  润新知