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]
原文地址:https://www.cnblogs.com/qing-chen/p/7685121.html