SlideShare a Scribd company logo
DO MORE THAN ONE
 THING AT THE TIME
         the Python way!



             Jaime Buelta
WHY?
SLICE A PROBLEM TO
SOLVE IT USING MORE
    RESOURCES
SAME THING FOR DIFFERENT ACTORS
DIFFERENT THINGS FOR THE SAME ACTOR
DOING MORE THAN ONE
  THING IS TOUGH
CHOOSE WISELY
THREADS
THREADS IN PYTHON

     module threading




      module thread
THREAD EXAMPLE
import threading
ITERATIONS = 1000000


class Example1(threading.Thread):

    def __init__(self, num):
        self.num = num
        super(Example1, self).__init__()

    def run(self):

        for i in xrange(ITERATIONS):
            pass


def main():
    for j in xrange(10):
        t = Example1(j)
        t.start()


if __name__ == '__main__':
    main()
TIMERS
from threading import Timer
DELAYED_TIME = 10.5


def delayed():
    print 'This call is delayed'

t = Timer(10.5, delayed)
t.start()

t.cancel() # Cancels the execution
PROCESSES
YE OLDE FORK
MULTIPROCESS MODULE
import multiprocessing
ITERATIONS = 1000000


class Example1(multiprocessing.Process):

    def __init__(self, num):
        self.num = num
        super(Example1, self).__init__()

    def run(self):

        for i in xrange(ITERATIONS):
            pass


def main():
    for j in xrange(10):
        t = Example1(j)
        t.start()


if __name__ == '__main__':
    main()
OS ARE GREAT AT
 MULTITASKING
PROCESS COMMUNICATION
 NEEDS TO BE STRUCTURED


   but that is not necessarily a bad thing
ASYNCHRONOUS
 PROGRAMMING
Thread 1   Thread 2
Do more than one thing at the same time, the Python way
Task 1    Task 2   Task 3


                               The task will release
waiting                       control once they are
ready!                        blocked waiting for an
          done!                   input from IO
                   waiting
                   ready!    Callback

done!
                   done!
death by callback
EVENTLET
NUM_URLS = 1000
URL = 'http://www.some_address.com/'

urls = [URL] * NUM_URLS

import eventlet
from eventlet.green import urllib2


def fetch(url):
    return urllib2.urlopen(url).read()


pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
    do_something_with_result(body)
Asynchronous
programing is great
when the tasks are
   IO - Bound

  So the CPU is
 basically waiting...
Asynchronous
 programing is not
good when tasks are
   CPU - Bound




If one tasks enters on
  an infinite loop, the
    whole system is
        blocked
YESTERDAY THERE WAS A
TALK ABOUT ASYNC PYTHON
      PROGRAMMING
            Hope you attended, I did.
    If you don’t, you can watch it online later
THE INFAMOUS GIL
It doesn’t allow to run two threads at the same time, even if the
OS will do it.

Only one thread run. The rest will be blocked.
2 core machine
Thread A
Thread B
100,000,000 iterations

40 s


30 s


20 s


10 s


 0s
       1   10             100              1000   10000



                4 core machine
IS IT REALLY
A PROBLEM?
I WANT TO WATCH THIS YOUTUBE




  BUT I’M ALREADY LISTENING TO MUSIC
           AT THE SAME TIME

EEH, NOT AS BIG AS IT LOOKS
GIL MAKES CONCURRENT
PROGRAMMING MUCH EASIER




   And the problems are quite limited in practice
BUT MAYBE YOUR PROGRAM
    IS ONE OF THE FEW




  Avoid problems not using threads, but processes
threading      multiprocess       sequential


100,000ms



 10,000ms



  1,000ms



   100ms



    10ms



     1ms
       1000          10000     100000       1000000          10000000
Great, detailed talk
         “Understanding GIL”
            by David Beazly
http://www.dabeaz.com/python/UnderstandingGIL.pdf
AVOID PROBLEMS
SIMPLE ARCHITECTURE
ALL PYTHON OPERATIONS
      ARE ATOMIC
     Hey, that’s what the GIL is for
LOCKING TO
BE USED WITH
   EXTREME
  CAUTION
 If you need to set exclusive
  sections, you are probably
        doing it wrong
BUT WHEN I
 DO, I USE WITH

from threading import Lock
my_lock = Lock()

def some_function(args):

    with my_lock:
        protected_section()
USE QUEUES
  (AND PIPES)
PROCESS
THE TASK
 WITH
WORKERS
LIMIT THE NUMBERS!!!
THREAD COORDINATION IS HELL
Main periodic thread

              task A

              task B

              task C

              task D


Main periodic thread


Main periodic thread
but that’s probably not the best use of Python
QUESTIONS?
                       THANKS
                          FOR
                         YOUR
                    ATTENTION
                    @jaimebuelta
    wrongsideofmemphis.wordpress.com

More Related Content

What's hot (20)

PDF
streamparse and pystorm: simple reliable parallel processing with storm
Daniel Blanchard
 
PDF
Understanding greenlet
Saúl Ibarra Corretgé
 
KEY
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
PDF
Golang concurrency design
Hyejong
 
PDF
Making fitting in RooFit faster
Patrick Bos
 
PDF
Global Interpreter Lock: Episode III - cat < /dev/zero > GIL;
Tzung-Bi Shih
 
PDF
[Pycon 2015] 오늘 당장 딥러닝 실험하기 제출용
현호 김
 
PDF
Using Python3 to Build a Cloud Computing Service for my Superboard II
David Beazley (Dabeaz LLC)
 
PPT
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
Fantix King 王川
 
PDF
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
PDF
concurrency
Jonathan Wagoner
 
PDF
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
PyNSK
 
PDF
Golang design4concurrency
Eduardo Ferro Aldama
 
PPTX
Kotlin coroutines and spring framework
Sunghyouk Bae
 
PDF
Python twisted
Mahendra M
 
PDF
Current State of Coroutines
Guido Pio Mariotti
 
PDF
Down the Rabbit Hole
Charles Nutter
 
PDF
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
PDF
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Graham Dumpleton
 
PDF
The Year of JRuby - RubyC 2018
Charles Nutter
 
streamparse and pystorm: simple reliable parallel processing with storm
Daniel Blanchard
 
Understanding greenlet
Saúl Ibarra Corretgé
 
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
Golang concurrency design
Hyejong
 
Making fitting in RooFit faster
Patrick Bos
 
Global Interpreter Lock: Episode III - cat < /dev/zero > GIL;
Tzung-Bi Shih
 
[Pycon 2015] 오늘 당장 딥러닝 실험하기 제출용
현호 김
 
Using Python3 to Build a Cloud Computing Service for my Superboard II
David Beazley (Dabeaz LLC)
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
Fantix King 王川
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
concurrency
Jonathan Wagoner
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
PyNSK
 
Golang design4concurrency
Eduardo Ferro Aldama
 
Kotlin coroutines and spring framework
Sunghyouk Bae
 
Python twisted
Mahendra M
 
Current State of Coroutines
Guido Pio Mariotti
 
Down the Rabbit Hole
Charles Nutter
 
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Graham Dumpleton
 
The Year of JRuby - RubyC 2018
Charles Nutter
 

Viewers also liked (20)

PPTX
Flask and Paramiko for Python VA
Enrique Valenzuela
 
KEY
Use git the proper way
Jaime Buelta
 
PDF
Utopia Kindgoms scaling case: From 4 to 50K users
Jaime Buelta
 
ODP
Use of django at jolt online v3
Jaime Buelta
 
PDF
Database madness with_mongoengine_and_sql_alchemy
Jaime Buelta
 
PDF
Make beautiful Python code
Jaime Buelta
 
PPTX
Django deployment best practices
Erik LaBianca
 
PDF
Ansible on AWS
Diego Pacheco
 
PDF
Django rest framework in 20 minuten
Andi Albrecht
 
PDF
Towards Continuous Deployment with Django
Roger Barnes
 
PDF
Two scoops of Django - Security Best Practices
Spin Lai
 
PDF
Pythonic Deployment with Fabric 0.9
Corey Oordt
 
PDF
Django REST Framework
Load Impact
 
PDF
Building a platform with Django, Docker, and Salt
baremetal
 
PDF
Life in a Queue - Using Message Queue with django
Tareque Hossain
 
PDF
Django in the Real World
Jacob Kaplan-Moss
 
KEY
Scaling Django
Mike Malone
 
PDF
12 tips on Django Best Practices
David Arcos
 
PPT
Ansible presentation
John Lynch
 
PPT
Introduction to SSH
Hemant Shah
 
Flask and Paramiko for Python VA
Enrique Valenzuela
 
Use git the proper way
Jaime Buelta
 
Utopia Kindgoms scaling case: From 4 to 50K users
Jaime Buelta
 
Use of django at jolt online v3
Jaime Buelta
 
Database madness with_mongoengine_and_sql_alchemy
Jaime Buelta
 
Make beautiful Python code
Jaime Buelta
 
Django deployment best practices
Erik LaBianca
 
Ansible on AWS
Diego Pacheco
 
Django rest framework in 20 minuten
Andi Albrecht
 
Towards Continuous Deployment with Django
Roger Barnes
 
Two scoops of Django - Security Best Practices
Spin Lai
 
Pythonic Deployment with Fabric 0.9
Corey Oordt
 
Django REST Framework
Load Impact
 
Building a platform with Django, Docker, and Salt
baremetal
 
Life in a Queue - Using Message Queue with django
Tareque Hossain
 
Django in the Real World
Jacob Kaplan-Moss
 
Scaling Django
Mike Malone
 
12 tips on Django Best Practices
David Arcos
 
Ansible presentation
John Lynch
 
Introduction to SSH
Hemant Shah
 
Ad

Similar to Do more than one thing at the same time, the Python way (20)

PDF
Multiprocessing.pdf..............,.......
Bhaveshmali28
 
PDF
Multiprocessing.............,...........
Bhaveshmali28
 
PPTX
Python UNIT-IV Multi Threading B.Tech CSE
SrinuTelugu
 
PDF
Concurrency in Python
konryd
 
PDF
Joblib: Lightweight pipelining for parallel jobs (v2)
Marcel Caraciolo
 
PDF
Concurrency in Python
Mosky Liu
 
PDF
MultiThreading in Python
SRINIVAS KOLAPARTHI
 
PDF
Understanding the Python GIL
David Beazley (Dabeaz LLC)
 
PDF
Python programming : Threads
Emertxe Information Technologies Pvt Ltd
 
PDF
Multithreaded_Programming_in_Python.pdf
giridharsripathi
 
PPTX
Pycon11: Python threads: Dive into GIL!
Chetan Giridhar
 
PDF
GIL - Concurrency & Parallelism in Python
Piyus Gupta
 
PDF
Global Interpreter Lock: Episode I - Break the Seal
Tzung-Bi Shih
 
PPTX
MULTI THREADING.pptx
KeerthanaM738437
 
PPTX
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
PDF
Concurrency and Python - PyCon MY 2015
Boey Pak Cheong
 
PDF
Asynchronous Python A Gentle Introduction
PyData
 
PDF
25 must know python for Interview by Tutort Academy
yashikanigam1
 
Multiprocessing.pdf..............,.......
Bhaveshmali28
 
Multiprocessing.............,...........
Bhaveshmali28
 
Python UNIT-IV Multi Threading B.Tech CSE
SrinuTelugu
 
Concurrency in Python
konryd
 
Joblib: Lightweight pipelining for parallel jobs (v2)
Marcel Caraciolo
 
Concurrency in Python
Mosky Liu
 
MultiThreading in Python
SRINIVAS KOLAPARTHI
 
Understanding the Python GIL
David Beazley (Dabeaz LLC)
 
Python programming : Threads
Emertxe Information Technologies Pvt Ltd
 
Multithreaded_Programming_in_Python.pdf
giridharsripathi
 
Pycon11: Python threads: Dive into GIL!
Chetan Giridhar
 
GIL - Concurrency & Parallelism in Python
Piyus Gupta
 
Global Interpreter Lock: Episode I - Break the Seal
Tzung-Bi Shih
 
MULTI THREADING.pptx
KeerthanaM738437
 
MULTI-THREADING in python appalication.pptx
SaiDhanushM
 
Concurrency and Python - PyCon MY 2015
Boey Pak Cheong
 
Asynchronous Python A Gentle Introduction
PyData
 
25 must know python for Interview by Tutort Academy
yashikanigam1
 
Ad

Recently uploaded (20)

PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

Do more than one thing at the same time, the Python way

Editor's Notes

  • #2: \n
  • #3: The first point is, why complicate the code trying to do more than one thing at the same time. The answer is to better use the resources. We need spare resources to start with\n\nThe typical applications that need these kind of techniques are three (divide a big tasks into several computers/cores, do the same thing for different actors, do different things for the same actor)\n
  • #4: The typical example is crunching numbers. Render a movie, data mining, etc. Usually can be treated as the next case (do the same thing more than once) with an algorithm that works with parts of the data.\n
  • #5: Do the same thing, for different actors\n Web server\n Different tabs on a web browser\n
  • #6: Do different things for the same actor (usually some coordination is needed, more later):\n Game (AI of each enemy, render image, sound)\n
  • #7: Debug can be very tricky, you’ve been advised. If coordination is needed, that can be tricky. If only one thing is do (several times), the complexity is highly reduced due help from the Operative System\n
  • #8: There are several ways of execute code concurrently, we’ll discuss threads, processes and asynchronous programming\n
  • #9: \n
  • #10: module thread\n Low level, in general is better avoid it\n module threading\n Higher level. More functionality\n
  • #11: \n
  • #12: \n
  • #13: \n
  • #14: A long, long time ago, that was the way of dealing with multiprocessing\nOnly available on Unix machines\nYou can fork using os.fork() in Python!\nFork is not in common use anymore due problems (fork bomb, etc)\n
  • #15: \n
  • #16: OS are very good at multitasking (and have been for some time). Communication can be achieved through ports, files, pipes, external queues, etc...\nBe radical, use more than one program\n
  • #17: Threads share all the memory, so they can access whatever. That is good (no communication overhead), but can lead to abuse and instability. \n
  • #18: it is the new cool technology, and there has been some recent uses, like NodeJS\n
  • #19: On a thread model, you have a supervisor (OS) that will stop one thread and execute the other, transparently for the program\n
  • #20: On asynchronous programing, every task is waiting for the others to end their dance to get on the dance floor\n
  • #21: Or voluntarily releasing control (sleep, yield, etc). The typical way of calling the next block is to add callbacks to the code (when this result is available, use it as input for this code).\n
  • #22: Callbacks make the code hard to follow and debug\n
  • #23: No threads! All the fetch functions start, there is no need for callbacks, the urlopen call will yield and resume at the same point\n
  • #24: The typical example is a web app, which normally takes time in get data from a DB and spend a small amount of time in composing the response.\nYou can keep a huge number of connections, like in chat servers, etc.\n
  • #25: Number crunching, 3d calculations, etc... In a threaded model, the rest of the thread will be executed from time to time.\n
  • #26: Use of Twisted and Tornado a some Node.js\n
  • #27: \n
  • #28: This will only happen on multicore processors.There is some overhead on the blocking. It also make UNIX signals to act weird (CTRL + C example)\n
  • #29: The OS could (and probably do, depending on the load) set a thread to run on each core.\n
  • #30: Num iterations is constant, with different threads. Increasing the number of threads magnifies the problem, as adds more overhead. Adding threads adds MORE time instead of reducing it.\n
  • #31: \n
  • #32: it is a very “first world problem”. It is only causing problems on a subset of programs, in general the effects are limited.\n
  • #33: Only if CPU-bound, multithread program is running on a multicore machine, you need to worry.\nEven one CPU bound thread can have an effect due overhead and could be more efficient to use sequential programming\n\n
  • #34: \n
  • #35: time vs iterations for 10 threads/processes\n
  • #36: He has a couple more articles on his web page www.dabeaz.com\n
  • #37: In general, for concurrent programming\n
  • #38: probably true for all software development\n\nkeep the tasks separated and reduce communication between elements\n\n\n
  • #39: That also includes C extensions. You don’t need a lock for reads, only for writes that are not a single python operation.\n
  • #40: Python should be enough for most of the situations. Think carefully if you need a lock, mutex or semaphore\n\n\n
  • #41: \n
  • #42: There are different kind of Queues, like LIFO, FIFO, Priority, etc. multiprocess has also queues.\nExternal queues can also be useful (RabbitMQ, AMQP, etc)\nA pipe is a queue with one input and one output.\n
  • #43: \n
  • #44: Limit the number of workers. Unlimited workers is unsafe and can block the system.\n\nA lot of threads can be worse than less threads. Do some tests to find the sweet spo\n
  • #45: Thread coordination is very difficult. Try to create and destroy short-lived threads instead.\n
  • #46: This structure is typical of games (and real time systems)\n\nEach interval (1 second), you evaluate the needs and throw the needed threads (or execute sequentially)\nThe main periodic thread can cancel next time threads that haven’t finished their task.\n\nKill unused threads\n
  • #47: So consider using other languages...\n
  • #48: \n