@adam_englander
Concurrent Programming in
Python
Programming the multi-verse
@adam_englander
Threading
• Thread-Local can be used for global data only accessible by a
single thread.
• Semaphores and locks prevent simultaneous access of memory.
Python’s with statement makes it a lot cleaner than many languages.
• Events and Barriers allow for easy interprocess coordination.
@adam_englander
Processes
• Process class allows for spawning and forking of processes from a
parent process.
• Popular for multi-tasking in scripts as you are simply executing a
command rather Threading which runs code.
• Provides pipes, queues, shared memory, and server processes for
interprocess communication.
• Allows for worker pools to manage resource utilization.
@adam_englander
Subprocesses
• Run other scripts from a main script
• Uses popen to open other scripts
• Allows for better error handling of subscripts
• Allows for waiting on the subscript to complete
@adam_englander
Concurrent
• Uses Futures
• Can use Thread Pools or Process Pools
• Allows for asynchronous function programming
• Works just like any other language with Futures/Promises
@adam_englander
Suggestions
• For scripts, uses Subprocess
• For all but the simplest of applications, use a concurrent framework
like curio, Tornado, Twisted, etc.
@adam_englander
Process Example
from multiprocessing import Process

import os

from random import randint

from time import sleep





def start():

print("Hello from pid", os.getpid())

sleep(randint(1, 3))

print("Goodbye from pid", os.getpid())

exit()



print("Hello from master pid", os.getpid())

for i in range(1, 5):

p = Process(target=start)

p.start()

print("Goodbye from master pid", os.getpid())
@adam_englander
Subprocess Example
import subprocess



print("nnManaged exec error")

p = subprocess.Popen(
[“/not/a/valid/script"],
shell=True,
stderr=subprocess.PIPE)

p.wait()

print(p.returncode, p.stderr.read())
@adam_englander
Curio
• High concurrency framework with no asynchronous I/O
• Utilizes core asynchronous and concurrency libraries available in
Python 3.5+
• Simplifies concurrent programming
• Highly performant
@adam_englander
Demos!
@adam_englander
Resources
• http://curio.readthedocs.io/
• https://docs.python.org/3/library/concurrency.html

Concurrent Programming in Python