摇滚吧!多进程!

摇滚吧!多进程

由于cpython GIL的特性,在单核下是完美的,但是面对多核,老爹的推荐是开启多进程,所以要发挥多核最好利用多进程

什么是进程

进程是程序执行中资源分配的基本单元。程序执行说明了他是动态的,就会有等待和执行,僵尸等状态。而资源分配就是指的堆栈,数据段,信号等。

进程的创建

from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',)) # 获得句柄
    p.start() # 运行进程
    p.join() # 等待子进程退出

当调用Process的时候,实际并没有创建子进程,只是创建了一个关联句柄,这个句柄包含当前环境的进程ID,就是父进程iD,子进程的标识,子进程启动之后的任务,还有参数传递。

当你调用start函数执行的时候,就会调用fork创建子进程,而子进程就会执行“_bootstrap”函数,并最终调用"run"方法,如果run方法不是循环,那么执行完成就会退出了。run方法默认是执行你之前填入的target方法和参数的,target(*args, **kwargs)。

join实际上是父进程等待子进程完成退出的意思。子进程的默认计数是从1开始的。

第二种创建进程的方法

 from multiprocessing import Process

  class Worker(Process):
      def __init__(self, *args, **kwargs):
          """可定制参数"""
          super(Worker, self).__init__(*args, **kwargs)

      def run(self):
          """可重写,比如不通过输入参数来指定,可以通过队列来获取数据"""
          print("I am rocking")
          super(Worker, self).run()

  def f(name):
      print(" hello world!:", name)

  if __name__ == "__main__":
      w = Worker(target=f, args=("Bomb",) )
      w.start()
      w.join()

为什么我一般不用pool而采用process,如果只是简单类似于map计算,是可以使用map的,但是面对复杂的业务,我会选择process,因为自己根据业务控制行为。

常用属性

p.run# 主要用于overrite的方法
p.start() # 创建子进程
p.join() # 父进程等待子进程完成
p.name # 子进程的名字
p.is_alive() # 查看子进程是否存活
p.pid# 子进程起来之后,才有值
p.terminate() #杀死子进程

进程的通讯

进程间的通讯基本都是共享内存,只是形式不一样,Queue都是基于pipe实现的。甚至于有的加了锁机制,保证数据同步,比如queue就是线程或者进程安全的

Pipe

返回两个可连接对象

from multiprocessing import Process, 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()   # prints "[42, None, 'hello']"
    p.join()

Queue

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()    # prints "[42, None, 'hello']"
    p.join()

共享状态Value,Array,Copy对象

https://docs.python.org/2/library/ctypes.html#module-ctypes

from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
from ctypes import Structure, c_double

class Point(Structure):
    _fields_ = [('x', c_double), ('y', c_double)]

def modify(n, x, s, A):
    n.value **= 2
    x.value **= 2
    s.value = s.value.upper()
    for a in A:
        a.x **= 2
        a.y **= 2

if __name__ == '__main__':
    lock = Lock()

    n = Value('i', 7)
    x = Value(c_double, 1.0/3.0, lock=False)
    s = Array('c', 'hello world', lock=lock) # lock在于多个并发写时,保证数据的一致性
    A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

    p = Process(target=modify, args=(n, x, s, A))
    p.start()
    p.join()

    print n.value
    print x.value
    print s.value
    print [(a.x, a.y) for a in A]

共享状态Managers

managers是一个管理资源的进程,支持的类型 dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Queue, Value and [Array](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Array,算是一个代理,其他进程通过这个服务进程获取数据。优势就是支持多种类型的资源,缺点就是得开个进程,如果这个进程挂了,就完蛋了。

from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
from ctypes import Structure, c_double

class Point(Structure):
    _fields_ = [('x', c_double), ('y', c_double)]

def modify(n, x, s, A):
    n.value **= 2
    x.value **= 2
    s.value = s.value.upper()
    for a in A:
        a.x **= 2
        a.y **= 2

if __name__ == '__main__':
    lock = Lock()

    n = Value('i', 7)
    x = Value(c_double, 1.0/3.0, lock=False)
    s = Array('c', 'hello world', lock=lock) # lock在于多个并发写时,保证数据的一致性
    A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

    p = Process(target=modify, args=(n, x, s, A))
    p.start()
    p.join()

    print n.value
    print x.value
    print s.value
    print [(a.x, a.y) for a in A]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 必备的理论基础 1.操作系统作用: 隐藏丑陋复杂的硬件接口,提供良好的抽象接口。 管理调度进程,并将多个进程对硬件...
    drfung阅读 3,628评论 0 5
  • Python 3的多进程 多进程库名叫multiprocessing。有几点记录一下: multiprocessi...
    小温侯阅读 3,505评论 0 2
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 3,059评论 0 9
  • 进程、进程的使用、进程注意点、进程间通信-Queue、进程池Pool、进程与线程对比、文件夹拷贝器-多任务 1.进...
    Cestine阅读 951评论 0 0
  • 一、总体内容 1.1、进程、程序的概念 1.2、使用 Process 完成多进程- multiprocessing...
    IIronMan阅读 786评论 0 1