python 多進程

python多線程 不適合cpu密集操做型的任務 適合io操做密集型的任務。python

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() 

 運行結果ide

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

 在進程裏面啓動線程spa

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]
相關文章
相關標籤/搜索