码迷,mamicode.com
首页 > 编程语言 > 详细

进程线程

时间:2016-03-17 19:39:12      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:多进程多线程

多进程

创建子进程

import os
print(‘Process(%s) start...‘ % os.getpid())
pid = os.fork()
if pid == 0:
    print("I am child process (%s) and my parent is %s.‘ %(os.getpid(), os.getppid()))
else:
    print(‘I (%s) just created a child process(%s).‘ %(os.getpid(), pid))

python创建子进程是封装了系统的fork调用。


python中创建跨平台的多进程应用,使用multiprocessing模块。

from multiprocessing import Process
import os

def run_proc(name):
    print("Run child process %s (%s)...‘ % (name, os.getpid()))
    
if __name__=‘__main__‘:
    print("Parent process %s.‘ % os.getpid())
    p = Process(target=run_proc, args = (‘test‘, ))
    print(‘child process will start.‘)
    p.start()
    p.join()
    print(‘child process end.‘)

创建子进程,只需要传入一个执行函数和函数的参数,创建一个process实例用start()方法启动,比fork()简单。join()可以等待子进程结束后再继续往下运行,用于进程间的同步。


Pool -- 进程池

from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print("Run task %s (%s)...‘ % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print("Task %s run %0.2f seconds.‘ % (name, (end - start)))
    
    
if __name__ == ‘__main__‘:
    print("Parent process %s.‘ % os.getpid())
    p = Pool(4)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print("Waiting for all subprocesses done...‘)
    p.close()
    p.join()
    print(‘All subprocesses done.‘)

Pool对象调用join()会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的process了。


subprocess -- 启动一个子进程,控制其输入和输出。

子进程需要输入则使用communicate()方法


进程间通信 -- Queue  Pipes

在父进程中创建两个子进程,一个向queue写,一个从queuq读。

from multiprocessing import Process, Queue
import os, time, random

def write(q):
    print("Process to write: %s‘ % os.getpid())
    for value in [‘A‘, ‘B‘, ‘C‘]:
        print(‘put %s to queue...‘ % value)
        q.put(value)
        time.sleep(random.random())
        
def read(q):
    print(‘Process to read: %s‘ % os.getpid())
    while True:
        value = q.get(True)
        print(‘Get %s from queue.‘ % value)

        
if __name__ == ‘__main__‘:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    pw.start()
    pr.start()
    pw.join()
    pr.terminate()


多线程


















进程线程

标签:多进程多线程

原文地址:http://ting2junshui.blog.51cto.com/975290/1752289

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!