1. Use Pool To create a process

from multiprocessing import Pool
def f(n):
return n*n
if __name__=="__main__":
p=Pool(5)
a=range(10)
print(p.map(f,a))

p.map Will a The data in the list circulates to the user in turn f function . But when a function needs two arguments , This method is not applicable .

2. Use Process To create a process

def info(title):
print title
print 'module name:', __name__
if hasattr(os, 'getppid'): # only available on Unix
print 'parent process:', os.getppid()
print 'process id:', os.getpid() def f(name):
info('function f')
print 'hello', name if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join() # Serial

3. Use Pool.apply_async( asynchronous )

from multiprocessing import Pool
import time def f(n):
print n*n
time.sleep(1)
return n*n if __name__ == '__main__':
p = Pool(processes=5)
res_list = []
for i in range(10):
res = p.apply_async(f,[i,])
res_list.append(res) for item in res_list:
print item.get()

Three ways to share memory

1. Use multiprocessing Medium Queue( take Queue Encapsulates the )

from multiprocessing import Process, Queue
import Queue as Q2
def f(q,n):
q.put([n, 'hello'])
print q.get()
if __name__ == '__main__':
q = Q2.Queue()
for i in range(5):
p = Process(target=f, args=(q,i))
p.start()
# print q.get() # prints "[42, None, 'hello']" from multiprocessing import Process, Lock
import time
def f(i):
# l.acquire()
time.sleep(1)
print 'hello world', i
# l.release() if __name__ == '__main__':
# lock = Lock()
for num in range(10):
Process(target=f, args=[num]).start()

2. Use values and array( Poor flexibility , It is not recommended to use )

from multiprocessing import Process, Value, Array
def f(n, a):
n.value = 3.1415927
for i in range(len(a)):
a[i] = -a[i] if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10)) p = Process(target=f, args=(num, arr))
p.start()
p.join() print num.value
print arr[:]

3. Use Manager

from multiprocessing import Process, Manager
def f(d, l):
d[1] = ''
d[''] = 2
d[0.25] = None
l.reverse() if __name__ == '__main__':
manager = Manager() d = manager.dict()
l = manager.list(range(10)) p = Process(target=f, args=(d, l))
p.start()
p.join() print d
print l

python More articles on how processes create and share content

  1. Python Created in ndarrary Of 20 Medium method

    A complete example of this article : Complete sample code This paper introduces the basic . Common creation ndarrary In many ways , With sample code . One . adopt ndarray establish import numpy as np 1.1 One dimensional array a = np.a ...

  2. python How to identify the content of the QR code

    There are many ways to identify QR code links , So how to use python How to realize recognition ? Please look at the following code : from pyzbar.pyzbar import decode from PIL import Image i ...

  3. python To create a file to write content

    https://www.cnblogs.com/evablogs/p/7096686.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2 ...

  4. python How to enter content from the keyboard in raw_input() and input() The difference between

    raw_input() The output is a string Input() What to type in , Output is what

  5. [ python ] Process operation

    Catalog ( See table of contents navigation on the right )- 1. Preface - 2. multiprocess modular - 2.1 multiprocess.Process modular     - 2.2 Use Process Module creation process     - 2. ...

  6. Python Create functions dynamically 【 turn 】

    There are similar problems in Zhihu I came across a problem by chance , The idea is to create it dynamically Python Function to solve , So we investigated the dynamic creation Python Function method . Definition lambda function stay Python In the definition of lambda The function is very simple ...

  7. 【 Fundamentals of network programming 】Linux Next process communication mode ( Shared memory , The Conduit , Message queue ,Socket)

    In online courses , There is talk about Socket Programming , about tcp Part of the explanation , In order to deepen our understanding of , I wrote Linux The next process Socket signal communication , In the process of learning , I've come into contact with several other ways . Make a note of . Pipeline communication ( anonymous , famous ) Guandaotong ...

  8. Python Sharing data between processes

    Recently, we encountered the problem of data sharing among multiple processes , I checked several blogs on the Internet, which are very good , Record it for future reference . One .Python multiprocessing Cross process object sharing   stay mp In the library , There are three ways to share objects across processes , The first one is ...

  9. python The whole development of the stack * Process theory Process creation * 180724

    One . Process theory 1. A process is the smallest unit of resource allocation . 2. Process scheduling means that multiple processes are scheduled under the control of the operating system CPU perform , To enjoy the resources of the computer . First come, first served Short job preferred Time slice rotation Multistage feedback queue 3. The process of process scheduling cannot ...

Random recommendation

  1. Visual Studio Code Chinese document ( One )- Quick start

    Visual Studio Code Is a lightweight but very powerful source code editor , What's important is that it's in Windows, OS X and Linux The operating system can run on the desktop .Visual Studio Code Built in right J ...

  2. 05_XML Parsing _02_dom4j Parsing encapsulates information into objects

    [person.xml] What to parse <?xml version="1.0" encoding="UTF-8"?> <students> ...

  3. What's going on in one place list Filter duplicate data in the collection , Take the last data added from the duplicate data

    1. First group the set ( Grouping field )2. In judging whether the number of groups is greater than  03. Greater than 0, There are duplicate data

  4. how js Compiled files dll For web phone

    1. Join a project solution :JSControl 2. Add... To this project js file (JScript1.js) Script content : function showAlert(){ alert('Today is a ...

  5. delegate vs event

    What are the differences between delegate and an event? An event declaration adds a layer of abstrac ...

  6. Spark SQL data source

    [TOC] background Spark SQL yes Spark A module of , For structured data processing . ++++++++++++++ +++++++++++++++++++++ | SQL | | Dataset API ...

  7. MVC A brief introduction to the development mode of

    MVCM model Model Entity classes and business and dao dao( Database access object )V view View jspC controller controller servlet effect : View and logic are separated Development design sequence 1. Design database ...

  8. linux in /dev/null command

    /dev/null : For empty device files >  : Where is the redirect , for example :echo "123" > /home/123.txt1  : Express stdout standard output , The system default is ...

  9. ( turn )RBAC The design of permission table

    RBAC(Role-Based Access Control, Role-based access control ), It means that the user is associated with the permission through the role . In short , A user has several roles , Each role has several permissions . such , Structural cause “ user - role - ...

  10. jvm Operating mechanism and volatile Keyword details

    Reference resources https://www.cnblogs.com/dolphin0520/p/3920373.html JVM Start process 1.java The command that the virtual machine starts is through java +xxx( Class name , This class has to have mai ...