多进程

IO操作不占用CPU,计算占用CPU。

一次IO就是一次请求,对于磁盘来说,一个IO就是读或者写磁盘的某个或者某段扇区,读写完了,这个IO也就结束了。IO操作:从硬盘上读一块数据,从网络上读一块数据,从内存里读一块数据。

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

一个n核CPU可以运行n个任务。

 

多进程示例:

import time,multiprocessing

def run(name):
    time.sleep(2)
    print('hello', name)

if __name__ == '__main__':
    for i in range(10):#多进程
        p = multiprocessing.Process(target=run, args=('bob %s'%i,))#启动一个进程
        p.start()

  结果:

hello bob 2
hello bob 5
hello bob 4
hello bob 6
hello bob 0
hello bob 3
hello bob 1
hello bob 7
hello bob 9
hello bob 8
View Code

 

进程中写上线程:

import time,multiprocessing,threading

def thread_run():
    print(threading.get_ident())#当前线程的id
def run(name):
    time.sleep(2)
    print('hello', name)
    t = threading.Thread(target=thread_run,)
    t.start()

if __name__ == '__main__':
    for i in range(10):#多进程
        p = multiprocessing.Process(target=run, args=('bob %s'%i,))#启动一个进程
        p.start()

  结果:

hello bob 3
4868
hello bob 2
4740
hello bob 0
4860
hello bob 7
2448
hello bob 8
4936
hello bob 6
4164
hello bob 1
4048
hello bob 5
2184
hello bob 9
4548
hello bob 4
2400
View Code

 

To show the individual process IDs involved, here is an expanded example

获取进程号:

注:每一个进程默认都有一个父进程,并且由父进程启动。
from multiprocessing import Process
import os


def info(title):
    print(title)
    print('module name:', __name__)#模块名
    print('parent process:', os.getppid())#父进程的id(每一个进程都有一个父进程,并且由父进程启动)
    print('process id:', os.getpid())#得到进程自己的id
    print("\n\n")


def f(name):
    info('\033[31;1m called from child process function info\033[0m')#在子进程中调用info()
    print('hello', name)

if __name__ == '__main__':
    info('\033[32;1mmain process line\033[0m')#在主进程中调用info()
    p = Process(target=f, args=('bob',))
    p.start()
    # p.join()

  结果:

main process line
module name: __main__
parent process: 3820
process id: 3372



 called from child process function info
module name: __mp_main__
parent process: 3372
process id: 4772



hello bob
View Code

 

posted @ 2018-08-06 11:09  耐烦不急  阅读(240)  评论(0编辑  收藏  举报