Python之多进程

python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了非常好用的多进程包multiprocessing,只需要定义一个函数,Python会完成其他所有事情。借助这个包,可以轻松完成从单进程到并发执行的转换。multiprocessing支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。

1. Process

创建进程的类:Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。name为别名。group实质上不使用。
方法:is_alive() 、join([timeout])、run()、start()、terminate()。其中,Process以start()启动某个进程。

is_alive():判断该进程是否还活着

join([timeout]):主进程阻塞,等待子进程的退出, join方法要在close或terminate之后使用。

run():进程p调用start()时,自动调用run()

属性:authkey、daemon(要通过start()设置)、exitcode(进程在运行时为None、如果为–N,表示被信号N结束)、name、pid。其中daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置。

例1.1:创建函数并将其作为单个进程

import multiprocessing
import time

def worker(interval):
    n = 5
    while n > 0:
        print("The time is {0}".format(time.ctime()))  #输出时间的格式
        time.sleep(interval)
        n -= 1

if __name__ == "__main__":
    p = multiprocessing.Process(target = worker, args = (3,))
    p.start()
    print "p.pid:", p.pid
    print "p.name:", p.name
    print "p.is_alive:", p.is_alive()

结果

1

2

3

4

5

6

7

8

p.pid: 8736

p.name: Process-1

p.is_alive: True

The time is Tue Apr 21 20:55:12 2015

The time is Tue Apr 21 20:55:15 2015

The time is Tue Apr 21 20:55:18 2015

The time is Tue Apr 21 20:55:21 2015

The time is Tue Apr 21 20:55:24 2015

例1.2:创建函数并将其作为多个进程

import multiprocessing
import time

def worker_1(interval):
    print "worker_1"
    time.sleep(interval)
    print "end worker_1"

def worker_2(interval):
    print "worker_2"
    time.sleep(interval)
    print "end worker_2"

def worker_3(interval):
    print "worker_3"
    time.sleep(interval)
    print "end worker_3"

if __name__ == "__main__":
  p1 = Process(target=worker_1, args=(6,))
   p2 = Process(target=worker_2, args=(4,))
    p3 = Process(target=worker_3, args=(2,))
  p1.start() p2.start() p3.start()
  print("The number of CPU is:" + str(cpu_count()))
     for p in active_children():
         print("child p.name:=%s" % p.name + "\tp.id=%s" % str(p.pid))
      print(p1.pid)
      print("END-----")

结果

1

2

3

4

5

6

7

8

9

10

11

The number of CPU is:4
child p.name:=Process-2 p.id=3864
child p.name:=Process-3 p.id=3256
child p.name:=Process-1 p.id=7336
7336
END-----
worker_1
worker_2
worker_3
end worker_3
end worker_2
end worker_1

例1.3:将进程定义为类

import multiprocessing
import time

class ClockProcess(multiprocessing.Process):
    def __init__(self, interval):
        multiprocessing.Process.__init__(self)
        self.interval = interval

    def run(self):
        n = 5
        while n > 0:
            print("the time is {0}".format(time.ctime()))
            time.sleep(self.interval)
            n -= 1

if __name__ == '__main__':
    p = ClockProcess(3)
    p.start()   

:进程p调用start()时,自动调用run()

结果

1

2

3

4

5

the time is Tue Apr 21 20:31:30 2015

the time is Tue Apr 21 20:31:33 2015

the time is Tue Apr 21 20:31:36 2015

the time is Tue Apr 21 20:31:39 2015

the time is Tue Apr 21 20:31:42 2015

例1.4:daemon程序对比结果

#1.4-1 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值