MULTIPROCESSING MODULE OF PYTHON. CPYTHON  CPython is the default, most-widely used implementation of the Python programming language.  CPython - single-threaded.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Gevent network library Denis Bilenko gevent.org. Problem statement from urllib2 import urlopen response = urlopen(' body = response.read()
1 Chapter 5 Concurrency: Mutual Exclusion and Synchronization Principals of Concurrency Mutual Exclusion: Hardware Support Semaphores Readers/Writers Problem.
Tutorial 5 Test1 Review. Q1: Which of the following is an operating system theme or model as defined in lectures?
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
CSCC69: Operating Systems
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Informationsteknologi Wednesday, September 26, 2007 Computer Systems/Operating Systems - Class 91 Today’s class Mutual exclusion and synchronization 
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
Concurrency: Mutual Exclusion and Synchronization Why we need Mutual Exclusion? Classical examples: Bank Transactions:Read Account (A); Compute A = A +
Reference: Message Passing Fundamentals.
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Multithreaded Programming in Python Nick Anastasia.
Review: Process Management Objective: –Enable fair multi-user, multiprocess computing on limited physical resources –Security and efficiency Process: running.
Concurrency CS 510: Programming Languages David Walker.
3.5 Interprocess Communication Many operating systems provide mechanisms for interprocess communication (IPC) –Processes must communicate with one another.
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
3.5 Interprocess Communication
A. Frank - P. Weisberg Operating Systems Introduction to Cooperating Processes.
The Structuring of Systems Using Upcalls David D. Clark Presenter: Haitham Gad.
Fundamentals of Python: From First Programs Through Data Structures
Programming Network Servers Topic 6, Chapters 21, 22 Network Programming Kansas State University at Salina.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings 1.
Distributed-Memory Programming Using MPIGAP Vladimir Janjic International Workhsop “Parallel Programming in GAP” Aug 2013.
Threads. Sequential control Sequential programs: begin execute end At any time, there is a single point of execution Threads: also structured as begin.
Python Concurrency Threading, parallel and GIL adventures Chris McCafferty, SunGard Global Services.
Concurrency, Mutual Exclusion and Synchronization.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Introduction to Concurrency.
Distributed System Concepts and Architectures 2.3 Services Fall 2011 Student: Fan Bai
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Threaded Programming in Python Adapted from Fundamentals of Python: From First Programs Through Data Structures CPE 401 / 601 Computer Network Systems.
The Mach System Abraham Silberschatz, Peter Baer Galvin, Greg Gagne Presentation By: Agnimitra Roy.
1 Program5 Due Friday, March Prog4 user_thread... amount = … invoke delegate transact (amount)... mainThread... Total + = amount … user_thread...
Kernel Locking Techniques by Robert Love presented by Scott Price.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Reusing threads.
Synchronization Methods in Message Passing Model.
CS533 - Concepts of Operating Systems 1 The Mach System Presented by Catherine Vilhauer.
Sistem Operasi © Sekolah Tinggi Teknik Surabaya 1.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
1 Prog4 user_thread... amount = … invoke delegate transact (amount)... mainThread... Total + = amount … user_thread... amount = … invoke delegate transact.
1 Chapter 9 Distributed Shared Memory. 2 Making the main memory of a cluster of computers look as though it is a single memory with a single address space.
C H A P T E R E L E V E N Concurrent Programming Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
Implementing Lock. From the Previous Lecture  The “too much milk” example shows that writing concurrent programs directly with load and store instructions.
SMP Basics KeyStone Training Multicore Applications Literature Number: SPRPxxx 1.
Implementing Mutual Exclusion Andy Wang Operating Systems COP 4610 / CGS 5765.
CS162 Section 2. True/False A thread needs to own a semaphore, meaning the thread has called semaphore.P(), before it can call semaphore.V() False: Any.
Pitfalls: Time Dependent Behaviors CS433 Spring 2001 Laxmikant Kale.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
CS703 - Advanced Operating Systems
Threaded Programming in Python
CS703 – Advanced Operating Systems
Background on the need for Synchronization
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
multiprocessing and mpi4py Python for computational science
Atomic Operations in Hardware
Computer Engg, IIT(BHU)
Concurrency: Mutual Exclusion and Synchronization
Process Synchronization
Implementing Mutual Exclusion
Concurrency: Mutual Exclusion and Process Synchronization
Implementing Mutual Exclusion
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
Presentation transcript:

MULTIPROCESSING MODULE OF PYTHON

CPYTHON  CPython is the default, most-widely used implementation of the Python programming language.  CPython - single-threaded  Cannot coordinate processes across compute nodes  Threads can only be coordinated on a single node

INTRO TO MULTIPROCESSING  Multiprocessing enables to spawn multiple processes, allowing programmer to fully leverage the computing power of multiple processors.  Solution to inter-node communication barrier  Thread-like interface to multiple processes  Ability to communicate between nodes enables efficient use of multiple cores  Slower than thread communication

 Thread is a thread of execution in a program.  Thread share the memory and state of the parent.  Process is an instance of a computer program that is being executed.  Processes share nothing but use inter-process communication mechanisms to communicate.

EXAMPLE Job Process

PROCESS  Process class is used to spawn processes by creating Process objects  Call start() function to start a new process  Call join() function to properly terminate the process. def printName(name): print 'hello', name if __name__ == '__main__': p = Process(target=printName, args=('foo', )) p.start() p.join()

COMMUNICATION AMONG PROCESSES  Pipe: send() recv()  Queue  Living in shared memory among processes  Semaphore and condition variables; like a gate to resource: >0 open, 0 closed

PIPE  Python multiprocessing library provides two classes for exchanging information between processes: Pipe and Queue.  Pipe is used between two processes and it returns a pair of connection objects which by default is duplex. def writer(conn): conn.send([5, 'foo', None]) conn.close() if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=writer, args=(child_conn, )) p.start() print parent_conn.recv()# will print [5, 'foo', None] p.join()

QUEUE  Queue is built on top of Pipe.  Used when we need to exchange objects between 2+ processes.  Use put() method to put the data.  Use get() method to get the data.

Example:  A reader and writer sharing a single queue  The writer sends a series of integers to the reader.  When the writer runs out of numbers, it sends 'DONE’.  The reader then knows to break out of the read loop.

from multiprocessing import Process, Queue import time def reader(queue): ## Read from the queue while True: msg = queue.get() #Read from the queue & do nothing if (msg == 'DONE'): break def writer(count, queue): ## Write to the queue for ii in xrange(0, count): queue.put(ii) #Write 'count' numbers into the queue queue.put('DONE')

if __name__=='__main__': for count in [10**4, 10**5, 10**6]: queue = Queue() # reader() reads from queue # writer() writes to queue reader_p = Process(target=reader, args=((queue),)) reader_p.daemon = True reader_p.start() #Launch reader as a process _start = time.time() writer(count, queue) #Send a lot to reader reader_p.join() # Wait for the reader to finish print "Sending %s numbers to Queue() took %s seconds" % (count, (time.time() - _start))

SYNCHRONIZATION PRIMITIVE (LOCK)  The synchronization primitives are used when we need share states between processes. import multiprocessing import sys global x def do_this(lock): global x lock.acquire() try: while(x < 300): x += 1 print x finally: lock.release()

def do_after(lock): lock.acquire() x = 450 try: while(x < 600): x += 1 print x finally: lock.release()

if __name__ == '__main__': x = 0 lock = multiprocessing.Lock() w = multiprocessing.Process(target=do_this, args=(lock, )) nw = multiprocessing.Process(target=do_after, args=(lock, )) w.start() nw.start() w.join() nw.join() ''' Outputs: '''

SHARE STATE BETWEEN PROCESSES  Shared memory  Server process  A Manager object control a server process that holds python objects and allow other process to access/manipulate them.  The shared object gets updated in all processes when anyone modifies it.

# Server from multiprocessing import BaseManager class QueueManager(BaseManager): pass QueueManager.register('get_queue', callable=lambda:queue) m = QueueManager(address=(‘', 50000)) s = m.get_server() s.serve_forever()

# Client from multiprocessing import BaseManager class QueueManager(BaseManager): pass QueueManager.register('get_queue') m = QueueManager(address=(' ', 50000)) m.connect queue = m.get_queue() queue.put('Hello World')

POOL  Python multiprocessing library provides a Pool class to implement multiprocessing for simple concurrent program.  Distribute the work among workers.  Collect the return value as a list.  Important methods:  apply/apply_async  map/map_async.

 Takes care of managing queue, processes, shared date/stats.  Makes it easy to implement quick/simple concurrent Python programs.

from multiprocessing import Pool def cube(x): return x**3 if __name__ == '__main__': pool = mp.Pool(processes=4) results = [pool.apply(cube, args=(x,)) for x \ in range(1,101)] print(results) Outputs: [1, 8, 27, 64, …, , , ]

REFERENCES  Python 2.6 documentation,  PyMOTW by Doug Hellmann,