zoukankan      html  css  js  c++  java
  • 【Rollo的Python之路】多线程实例

    多线程实例:

    共节省两秒时间,以最大的时间为准,小的时间就是省下来的时间。

    IO密集型项目,多线程可以节省时间,像爬虫这样的项目

    计算密集型项目,就是用C来代替python写。

    或者可以是协和+多进程。

    import threading
    import time
    from time import ctime,sleep
    
    def music(func):
        for i in range(2):
            print("I was listening to %s.%s" %(func,ctime()))
            sleep(1)
            print("end listening %s" % ctime())
    
    def movie(func):
        for i in range(2):
            print("I was at the %s %s" %(func,ctime()))
            sleep(5)
            print("end watch %s" % ctime())
    
    threads = []
    
    t1 = threading.Thread(target=music,args=("overstock",))
    threads.append(t1)
    t2 = threading.Thread(target=movie,args=("kill them all",))
    threads.append(t2)
    
    if __name__ =="__main__":
        for t in threads:
            t.start()
            print("all over %s" %ctime())
    
    
    执行结果:
    
    
    I was at the kill them all Thu May 23 21:26:14 2019
    all over Thu May 23 21:26:14 2019
    end listening Thu May 23 21:26:15 2019
    I was listening to overstock.Thu May 23 21:26:15 2019
    end listening Thu May 23 21:26:16 2019
    end watch Thu May 23 21:26:19 2019
    I was at the kill them all Thu May 23 21:26:19 2019
    end watch Thu May 23 21:26:24 2019

    单线程实例:

    import time
    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 movie(func):
        for i in range(2):
            print("I was at the %s %s" %(func,ctime()))
            sleep(5)
    
    
    if __name__ =="__main__":
        music(u'七里香')
        movie(u'kill them all')
    
    执行结果:
    #注意时间间隔
    
    I was listening to 七里香.Thu May 23 21:31:12 2019
    I was listening to 七里香.Thu May 23 21:31:13 2019
    I was at the kill them all Thu May 23 21:31:14 2019
    I was at the kill them all Thu May 23 21:31:19 2019
  • 相关阅读:
    【C++服务端技术】消息队列
    【C++服务端技术】智能锁
    【C++服务端技术】队列
    【C++服务端技术】对象池
    【面试攻略】C++面试-边锋
    【面试攻略】C++面试-成都星合互娱
    【面试攻略】C++面试-紫龙游戏
    服务器IO-HPSocket
    【面试攻略】C++面试-沐瞳游戏
    【面试攻略】C++面试-点点互动
  • 原文地址:https://www.cnblogs.com/rollost/p/10914684.html
Copyright © 2011-2022 走看看