I/O 密集型:多线程
计算密集型:多进程
Python中 进程的使用和线程使用,这里就不累述 基础和锁相关了,重点分享一下进程的数据共享
一般情况下,进程是数据隔离的,但是Python为大家准备了三种解除数据隔离的方法:
1、queues 进程的队列;
2、Arrey 数组,需要设置 统一的数据类型(数组中的所有元素数据类型必须统一),元素个数;
3、Manger.dict 特殊字典,没有数组的两个限制(数据类型,元素个数)。
queues
#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7
from multiprocessing import Process
from multiprocessing import queues
import multiprocessing
def foo(i,arg):
arg.put(i)
print('say hi',i,arg.qsize())
if __name__ == "__main__":
li = queues.Queue(20,ctx=multiprocessing)
for i in range(10):
p = Process(target=foo,args=(i,li,))
p.start()
Arrey
#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7
from multiprocessing import Process
from multiprocessing import queues
import multiprocessing
from multiprocessing import Array
def foo(i,arg):
# arg.put(i)
# print('say hi',i,arg.qsize())
arg[i] = i + 100
for item in arg:
print(item)
print('=======================')
if __name__ == "__main__":
# li = queues.Queue(20,ctx=multiprocessing)
li = Array('i',10)
for i in range(10):
p = Process(target=foo,args=(i,li,))
p.start()
Manager
#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7
from multiprocessing import Process
from multiprocessing import queues
import multiprocessing
from multiprocessing import Array
from multiprocessing import Manager
import time
def foo(i,arg):
# arg.put(i)
# print('say hi',i,arg.qsize())
arg[i] = i + 100
print(arg.values())
# for item in arg:
# print(item)
# print('=======================')
if __name__ == "__main__":
# li = queues.Queue(20,ctx=multiprocessing)
# li = Array('i',10)
obj = Manager()
li = obj.dict()
for i in range(10):
p = Process(target=foo,args=(i,li,))
p.start()
# p.join() #方式一,子进程执行完后,主进程在退
time.sleep(0.7)#方式二,设置主进程等待时间,等待子进程执行完成,相比,方式一更严谨