Concurrency

From CS 61A Wiki
Revision as of 19:04, 8 August 2014 by Stevencheng (Talk | contribs)


Jump to: navigation, search

Concurrency, or parallel computing, allows for multiple operations to be performed simultaneously. In the past, the speed of individual processor cores grew at an exponential rate, but due to power and thermal constraints, this increase came to an abrupt end. Since then, CPU manufacturers began to place cores in a single processor, allowing for more operations to be performed concurrently.

Parallelism in Python

Threading

In threading, multiple "threads" of execution exist within a single interpreter. Each thread executes code independently from the others, though they share the same data.

>>> import threading
>>> def thread_hello():
        other = threading.Thread(target=thread_say_hello, args=())
        other.start()
        thread_say_hello()
 
>>> def thread_say_hello():
        print('hello from', threading.current_thread().name)
 
>>> thread_hello()
hello from Thread-1
hello from MainThread

Multiprocessing

Multiprocessing allows a program to spawn multiple interpreters, or processes, each of which can run code independently, without sharing data.

>>> import multiprocessing
>>> def process_hello():
        other = multiprocessing.Process(target=process_say_hello, args=())
        other.start()
        process_say_hello()
 
>>> def process_say_hello():
        print('hello from', multiprocessing.current_process().name)
 
>>> process_hello()
hello from MainProcess
>>> hello from Process-1