zoukankan      html  css  js  c++  java
  • python 多进程

    python多线程 不适合cpu密集操作型的任务 适合io操作密集型的任务。

    multiprocessing 多进程

    import multiprocessing
    import time
    
    def run(name):
         print('hello',name)
    
    if __name__ == '__main__':
        p = multiprocessing.Process(target=run,args=('jim',))
        p.start() #hello jim
    

     起多个进程

    import multiprocessing
    import time
    
    def run(name):
         time.sleep(1)
         print('hello',name)
    
    if __name__ == '__main__':
        for i in range(10):
            p = multiprocessing.Process(target=run,args=('jim %s' %i,))
            p.start() 
    

     运行结果

    hello jim 0
    hello jim 3
    hello jim 2
    hello jim 1
    hello jim 6
    hello jim 7
    hello jim 4
    hello jim 8
    hello jim 5
    hello jim 9
    

     在进程里面启动线程

    import multiprocessing
    import time,threading
    
    def run1():
        print("当前线程[%s]"% threading.get_ident())
    
    def run(name):
         print('当前进程 ',name)
         t = threading.Thread(target=run1)
         t.start()
    
    if __name__ == '__main__':
        for i in range(10):
            p = multiprocessing.Process(target=run,args=(' %s' %i,))
            p.start()
    

     运行结果

    当前进程   2
    当前线程[8168]
    当前进程   1
    当前线程[2260]
    当前进程   0
    当前线程[2012]
    当前进程   3
    当前线程[716]
    当前进程   5
    当前线程[6888]
    当前进程   4
    当前线程[1504]
    当前进程   6
    当前线程[8096]
    当前进程   9
    当前线程[4576]
    当前进程   7
    当前线程[5368]
    当前进程   8
    当前线程[6284]
    
  • 相关阅读:
    树莓派开发实战(第2版)
    Windows 7+Office 2010综合应用培训教程
    Adobe Edge Animate CC
    从零开始学采购:供应商管理与采购过程控制
    iOS项目开发全程实录
    SEO搜索引擎实战详解
    Photoshop移动UI设计完全实例教程
    游戏开发物理学
    psd,
    放到 userdefault,而不是 cache里面,
  • 原文地址:https://www.cnblogs.com/qing-chen/p/7685121.html
Copyright © 2011-2022 走看看