Process locks and shared pools

Source: Internet
Author: User

One, Process lock

From multiprocessing import Process,lock

def lock_f (l,i):
L.acquire ()
Try
Print ("Multip-%s"% i)
Finally
L.release ()

If __name__== "__main__":
Lock = Lock ()
For NUM in range (10):
Process (Target=lock_f,args = (lock,num)). Start ()
Second, Process pool
From multiprocessing import Process,pool,freeze_support
Import Time
Import OS

def Foo (i):
time.sleep (1)
print ("In process!", Os.getpid ())
return i+100

def Bar (args):
print ("-->exec done!", Args,os.getpid ())

if __name__== "__main__":
pool = Pool (processes=2) #允许进程池同时放入2个进程;
print ("Main process pool:", Os.getpid ())
For I in Range (Ten):
#pool. Apply (func = foo,args= (i,)) #apply支持串行;
#pool. Apply_async (func=foo,args= (i)) #apply_async支持并行;
Pool.apply_async (func=foo,args= (i,), Callback=bar)

print ("end!")
pool.close ()
Pool.join () #进程池中进程, after execution, close again; If you look at the line, the program shuts down directly.

Process locks and shared pools

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.