首页 > 编程语言 > 详细

python--多进程

时间:2017-02-26 22:39:05      阅读:314      评论:0      收藏:0      [点我收藏+]

多进程:

import multiprocessing
import time

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

 

获取进程ID:

from multiprocessing import Process
import os

def info(title):
    print(title)
    print(‘module name:‘,__name__)
    print(‘parent process:‘,os.getppid())
    print(‘process id:‘,os.getpid())
    print(‘\n\n‘)

def f(name):
    info(‘\033[31;1mfunction f\033[0m‘)
    print(‘hello‘,name)

if __name__ == ‘__main__‘:
    info(‘\033[32;1mmain process line\033[0m‘)
    p = Process(target=f, args=(‘bob‘,))
    p.start()
    p.join()

 

进程间互访:

#进程队列互访
from multiprocessing import Process, Queue
def f(q):
    q.put([42, None, ‘hello‘])

if __name__ == ‘__main__‘:
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print(q.get())
    p.join()


#使用管道实现
from multiprocessing import Process, Queue, Pipe

def f(conn):
    conn.send([42, None, ‘hello‘])
    conn.close()

if __name__ == ‘__main__‘:
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print(parent_conn.recv())
    p.join()


#线程队列互访
import threading, queue
def f(q):
    q.put([42, None, ‘hello‘])

if __name__ == ‘__main__‘:
    q = queue.Queue()
    t = threading.Thread(target=f, args=(q,))
    t.start()
    print(q.get())
    t.join()

 

进程间交互之Manager:

from multiprocessing import Process, Queue, Manager
import os

def f(d, l):
    d[1] = ‘1‘
    d[‘2‘] = 2
    d[0.25] = None
    l.append(os.getpid())
    print(l)

if __name__ == ‘__main__‘:
    with Manager() as manager:
        d = manager.dict()

        l = manager.list(range(5))
        p_list = []
        for i in range(10):
            p = Process(target=f, args=(d, l))
            p.start()
            p_list.append(p)
        for res in p_list:
            res.join()

        print(‘d‘,d)
        print(‘l‘,l)

 

python--多进程

原文:http://www.cnblogs.com/guqing/p/6446102.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!