SlideShare a Scribd company logo
1 of 34
Download to read offline
Built-in solutions
     3-rd Party Solutions
                 Summary




Concurrency in Python
 Overview of current solutions

     Andrii V. Mishkovskyi


     December 28, 2009
    Andrii V. Mishkovskyi     Concurrency in Python
Built-in solutions   Based on system threads
        3-rd Party Solutions     Process-based
                    Summary      Coroutines




threading module

   Kernel threads
   Similar to JVM’s threading module
   Lots of synchronization primitives



       Andrii V. Mishkovskyi     Concurrency in Python
Built-in solutions   Based on system threads
         3-rd Party Solutions     Process-based
                     Summary      Coroutines




Global Interpreter Lock
    Simple locking mechanism
    Doesn’t allow execution of more
    than 1 thread at a time
    Unless it’s IO-bound thread
    CPU-bound threads don’t benefit
    from parallel execution
        Andrii V. Mishkovskyi     Concurrency in Python
Built-in solutions   Based on system threads
        3-rd Party Solutions     Process-based
                    Summary      Coroutines




multiprocessing module

   API similar to multithreading
   Operates on process level
   Nice way of avoiding GIL issues



       Andrii V. Mishkovskyi     Concurrency in Python
Built-in solutions   Based on system threads
        3-rd Party Solutions     Process-based
                    Summary      Coroutines




PEP 342

   Simple support through “enhanced
   generators”
   yield expression
   No built-in library or framework


       Andrii V. Mishkovskyi     Concurrency in Python
Twisted
               Built-in solutions   Stackless Python
           3-rd Party Solutions     Kamaelia
                       Summary      cogen
                                    Others


Twisted

    Emacs of Python concurrency
    Tons of unit tests
    Years of active development
    Supports almost every protocol
    there is

          Andrii V. Mishkovskyi     Concurrency in Python
Twisted example

 from twisted.internet import reactor, protocol
 class Echo(protocol.Protocol):
     def dataReceived(self, data):
         self.transport.write(data)
 factory = protocol.ServerFactory()
 factory.protocol = Echo
 reactor.listenTCP(8000, factory)
 reactor.run()
Twisted example

 from twisted.internet import reactor, protocol
 class Echo(protocol.Protocol):
     def dataReceived(self, data):
         self.transport.write(data)
 factory = protocol.ServerFactory()
 factory.protocol = Echo
 reactor.listenTCP(8000, factory)
 reactor.run()
Twisted example

 from twisted.internet import reactor, protocol
 class Echo(protocol.Protocol):
     def dataReceived(self, data):
         self.transport.write(data)
 factory = protocol.ServerFactory()
 factory.protocol = Echo
 reactor.listenTCP(8000, factory)
 reactor.run()
Twisted example

 from twisted.internet import reactor, protocol
 class Echo(protocol.Protocol):
     def dataReceived(self, data):
         self.transport.write(data)
 factory = protocol.ServerFactory()
 factory.protocol = Echo
 reactor.listenTCP(8000, factory)
 reactor.run()
Twisted example

 from twisted.internet import reactor, protocol
 class Echo(protocol.Protocol):
     def dataReceived(self, data):
         self.transport.write(data)
 factory = protocol.ServerFactory()
 factory.protocol = Echo
 reactor.listenTCP(8000, factory)
 reactor.run()
Twisted
             Built-in solutions   Stackless Python
         3-rd Party Solutions     Kamaelia
                     Summary      cogen
                                  Others


Stackless Python

    Patch to CPython to not use C stack
    Ability to monkeypatch existing
    codebase with “stackless sockets”
    100% compatible with CPython


        Andrii V. Mishkovskyi     Concurrency in Python
Stackless Example, part I
 import stackless
 import stacklesssocket
 stacklesssocket.install()
 import socket
 class Server(object):
     def __init__(self, conn):
         self.serversocket = 
            socket.socket(socket.AF_INET,
                           socket.SOCK_STREAM)
         self.serversocket.setsockopt(
                             socket.SOL_SOCKET,
                             socket.SO_REUSEADDR,
                             1)
         self.serversocket.bind(conn)
         self.serversocket.listen(5)
         stackless.tasklet(self.accept)()
Stackless Example, part I
 import stackless
 import stacklesssocket
 stacklesssocket.install()
 import socket
 class Server(object):
     def __init__(self, conn):
         self.serversocket = 
            socket.socket(socket.AF_INET,
                           socket.SOCK_STREAM)
         self.serversocket.setsockopt(
                             socket.SOL_SOCKET,
                             socket.SO_REUSEADDR,
                             1)
         self.serversocket.bind(conn)
         self.serversocket.listen(5)
         stackless.tasklet(self.accept)()
Stackless Example, part I
 import stackless
 import stacklesssocket
 stacklesssocket.install()
 import socket
 class Server(object):
     def __init__(self, conn):
         self.serversocket = 
            socket.socket(socket.AF_INET,
                           socket.SOCK_STREAM)
         self.serversocket.setsockopt(
                             socket.SOL_SOCKET,
                             socket.SO_REUSEADDR,
                             1)
         self.serversocket.bind(conn)
         self.serversocket.listen(5)
         stackless.tasklet(self.accept)()
Stackless Example, part II
     def accept(self):
         while self.serversocket.accept:
             (clientsocket, address) = 
                 self.serversocket.accept()
             stackless.tasklet(
                 self.manage)(clientsocket,
                              address)
             stackless.schedule()
     def manage(self, clientsocket, address):
         clientsocket.send(
             cliensocket.recv(4096))
 s = Server((’0.0.0.0’, 8000))
 stackless.run()
Stackless Example, part II
     def accept(self):
         while self.serversocket.accept:
             (clientsocket, address) = 
                 self.serversocket.accept()
             stackless.tasklet(
                 self.manage)(clientsocket,
                              address)
             stackless.schedule()
     def manage(self, clientsocket, address):
         clientsocket.send(
             cliensocket.recv(4096))
 s = Server((’0.0.0.0’, 8000))
 stackless.run()
Stackless Example, part II
     def accept(self):
         while self.serversocket.accept:
             (clientsocket, address) = 
                 self.serversocket.accept()
             stackless.tasklet(
                 self.manage)(clientsocket,
                              address)
             stackless.schedule()
     def manage(self, clientsocket, address):
         clientsocket.send(
             cliensocket.recv(4096))
 s = Server((’0.0.0.0’, 8000))
 stackless.run()
Twisted
             Built-in solutions   Stackless Python
         3-rd Party Solutions     Kamaelia
                     Summary      cogen
                                  Others


Kamaelia

    Developed by BBC Research
    Follows UNIX principles
    Components all the way round



        Andrii V. Mishkovskyi     Concurrency in Python
Kamaelia Example

 import Axon
 from Kamaelia.Chassis.ConnectedServer
     import SimpleServer
 class Echo(Axon.Component.component):
     def main(self):
         while 1:
             while self.dataReady("inbox"):
                  self.send(self.recv("inbox"),
                            "outbox")
             yield 1
 SimpleServer(protocol=Echo, port=1500).run()
Kamaelia Example

 import Axon
 from Kamaelia.Chassis.ConnectedServer
     import SimpleServer
 class Echo(Axon.Component.component):
     def main(self):
         while 1:
             while self.dataReady("inbox"):
                  self.send(self.recv("inbox"),
                            "outbox")
             yield 1
 SimpleServer(protocol=Echo, port=1500).run()
Kamaelia Example

 import Axon
 from Kamaelia.Chassis.ConnectedServer
     import SimpleServer
 class Echo(Axon.Component.component):
     def main(self):
         while 1:
             while self.dataReady("inbox"):
                  self.send(self.recv("inbox"),
                            "outbox")
             yield 1
 SimpleServer(protocol=Echo, port=1500).run()
Kamaelia Example

 import Axon
 from Kamaelia.Chassis.ConnectedServer
     import SimpleServer
 class Echo(Axon.Component.component):
     def main(self):
         while 1:
             while self.dataReady("inbox"):
                  self.send(self.recv("inbox"),
                            "outbox")
             yield 1
 SimpleServer(protocol=Echo, port=1500).run()
Twisted
             Built-in solutions   Stackless Python
         3-rd Party Solutions     Kamaelia
                     Summary      cogen
                                  Others


cogen

   Coroutine-based
   Extensible scheduler
   Quite low-level (if compared to
   Kamaelia)


        Andrii V. Mishkovskyi     Concurrency in Python
cogen example, part I

 from cogen.core import sockets
 from cogen.core import schedulers
 from cogen.core.coroutines import coroutine
 @coroutine
 def server():
     srv = sockets.Socket()
     srv.bind((0.0.0.0’, 8000))
     srv.listen(10)
     while True:
         conn, addr = yield srv.accept()
         m.add(handler, args=(conn, addr))
cogen example, part I

 from cogen.core import sockets
 from cogen.core import schedulers
 from cogen.core.coroutines import coroutine
 @coroutine
 def server():
     srv = sockets.Socket()
     srv.bind((0.0.0.0’, 8000))
     srv.listen(10)
     while True:
         conn, addr = yield srv.accept()
         m.add(handler, args=(conn, addr))
cogen example, part I

 from cogen.core import sockets
 from cogen.core import schedulers
 from cogen.core.coroutines import coroutine
 @coroutine
 def server():
     srv = sockets.Socket()
     srv.bind((0.0.0.0’, 8000))
     srv.listen(10)
     while True:
         conn, addr = yield srv.accept()
         m.add(handler, args=(conn, addr))
cogen example, part I

 from cogen.core import sockets
 from cogen.core import schedulers
 from cogen.core.coroutines import coroutine
 @coroutine
 def server():
     srv = sockets.Socket()
     srv.bind((0.0.0.0’, 8000))
     srv.listen(10)
     while True:
         conn, addr = yield srv.accept()
         m.add(handler, args=(conn, addr))
cogen example, part II

 @coroutine
 def handler(sock, addr):
     data = yield sock.read()
     yield sock.write(data)
     sock.close()
     return
 m = schedulers.Scheduler()
 m.add(server)
 m.run()
cogen example, part II

 @coroutine
 def handler(sock, addr):
     data = yield sock.read()
     yield sock.write(data)
     sock.close()
     return
 m = schedulers.Scheduler()
 m.add(server)
 m.run()
cogen example, part II

 @coroutine
 def handler(sock, addr):
     data = yield sock.read()
     yield sock.write(data)
     sock.close()
     return
 m = schedulers.Scheduler()
 m.add(server)
 m.run()
cogen example, part II

 @coroutine
 def handler(sock, addr):
     data = yield sock.read()
     yield sock.write(data)
     sock.close()
     return
 m = schedulers.Scheduler()
 m.add(server)
 m.run()
Twisted
              Built-in solutions   Stackless Python
          3-rd Party Solutions     Kamaelia
                      Summary      cogen
                                   Others


Others
    Concurrence – nice asynchrounous
    framework with async MySQL driver
    eventlet – based on coroutines,
    developed and used by “Second
    Life”
    py.execnet – distribute tasks over
    network
         Andrii V. Mishkovskyi     Concurrency in Python
Built-in solutions
      3-rd Party Solutions
                  Summary




GIL doesn’t harm 90% of the
existing code
But Twisted, Kamaelia and others
are often cleaner
Python is not Erlang, it’s better ;)


     Andrii V. Mishkovskyi     Concurrency in Python

More Related Content

What's hot

Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
Jeff Smith
 

What's hot (20)

The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 
Thread
ThreadThread
Thread
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
The Ring programming language version 1.8 book - Part 54 of 202
The Ring programming language version 1.8 book - Part 54 of 202The Ring programming language version 1.8 book - Part 54 of 202
The Ring programming language version 1.8 book - Part 54 of 202
 
Async I/O in Python
Async I/O in PythonAsync I/O in Python
Async I/O in Python
 
The Ring programming language version 1.8 book - Part 9 of 202
The Ring programming language version 1.8 book - Part 9 of 202The Ring programming language version 1.8 book - Part 9 of 202
The Ring programming language version 1.8 book - Part 9 of 202
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
Kotlin Coroutines Reloaded
Kotlin Coroutines ReloadedKotlin Coroutines Reloaded
Kotlin Coroutines Reloaded
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
Provisioning with OSGi Subsystems and Repository using Apache Aries and Felix
Provisioning with OSGi Subsystems and Repository using Apache Aries and FelixProvisioning with OSGi Subsystems and Repository using Apache Aries and Felix
Provisioning with OSGi Subsystems and Repository using Apache Aries and Felix
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 

Similar to Python concurrency: libraries overview

Twisted logic
Twisted logicTwisted logic
Twisted logic
ashfall
 

Similar to Python concurrency: libraries overview (20)

Twisted logic
Twisted logicTwisted logic
Twisted logic
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
 
Writing Redis in Python with asyncio
Writing Redis in Python with asyncioWriting Redis in Python with asyncio
Writing Redis in Python with asyncio
 
Stackless Python 101
Stackless Python 101Stackless Python 101
Stackless Python 101
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Building an inflight entertainment system controller in twisted
Building an inflight entertainment system controller in twistedBuilding an inflight entertainment system controller in twisted
Building an inflight entertainment system controller in twisted
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Tech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/O
Tech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/OTech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/O
Tech Webinar: AUMENTARE LA SCALABILITÀ DELLE WEB APP CON SERVLET 3.1 ASYNC I/O
 
Twisted is easy
Twisted is easyTwisted is easy
Twisted is easy
 
The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212The Ring programming language version 1.10 book - Part 102 of 212
The Ring programming language version 1.10 book - Part 102 of 212
 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
 
Ato2019 weave-services-istio
Ato2019 weave-services-istioAto2019 weave-services-istio
Ato2019 weave-services-istio
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioAll Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istio
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Python concurrency: libraries overview

  • 1. Built-in solutions 3-rd Party Solutions Summary Concurrency in Python Overview of current solutions Andrii V. Mishkovskyi December 28, 2009 Andrii V. Mishkovskyi Concurrency in Python
  • 2. Built-in solutions Based on system threads 3-rd Party Solutions Process-based Summary Coroutines threading module Kernel threads Similar to JVM’s threading module Lots of synchronization primitives Andrii V. Mishkovskyi Concurrency in Python
  • 3. Built-in solutions Based on system threads 3-rd Party Solutions Process-based Summary Coroutines Global Interpreter Lock Simple locking mechanism Doesn’t allow execution of more than 1 thread at a time Unless it’s IO-bound thread CPU-bound threads don’t benefit from parallel execution Andrii V. Mishkovskyi Concurrency in Python
  • 4. Built-in solutions Based on system threads 3-rd Party Solutions Process-based Summary Coroutines multiprocessing module API similar to multithreading Operates on process level Nice way of avoiding GIL issues Andrii V. Mishkovskyi Concurrency in Python
  • 5. Built-in solutions Based on system threads 3-rd Party Solutions Process-based Summary Coroutines PEP 342 Simple support through “enhanced generators” yield expression No built-in library or framework Andrii V. Mishkovskyi Concurrency in Python
  • 6. Twisted Built-in solutions Stackless Python 3-rd Party Solutions Kamaelia Summary cogen Others Twisted Emacs of Python concurrency Tons of unit tests Years of active development Supports almost every protocol there is Andrii V. Mishkovskyi Concurrency in Python
  • 7. Twisted example from twisted.internet import reactor, protocol class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run()
  • 8. Twisted example from twisted.internet import reactor, protocol class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run()
  • 9. Twisted example from twisted.internet import reactor, protocol class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run()
  • 10. Twisted example from twisted.internet import reactor, protocol class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run()
  • 11. Twisted example from twisted.internet import reactor, protocol class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run()
  • 12. Twisted Built-in solutions Stackless Python 3-rd Party Solutions Kamaelia Summary cogen Others Stackless Python Patch to CPython to not use C stack Ability to monkeypatch existing codebase with “stackless sockets” 100% compatible with CPython Andrii V. Mishkovskyi Concurrency in Python
  • 13. Stackless Example, part I import stackless import stacklesssocket stacklesssocket.install() import socket class Server(object): def __init__(self, conn): self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serversocket.bind(conn) self.serversocket.listen(5) stackless.tasklet(self.accept)()
  • 14. Stackless Example, part I import stackless import stacklesssocket stacklesssocket.install() import socket class Server(object): def __init__(self, conn): self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serversocket.bind(conn) self.serversocket.listen(5) stackless.tasklet(self.accept)()
  • 15. Stackless Example, part I import stackless import stacklesssocket stacklesssocket.install() import socket class Server(object): def __init__(self, conn): self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.serversocket.bind(conn) self.serversocket.listen(5) stackless.tasklet(self.accept)()
  • 16. Stackless Example, part II def accept(self): while self.serversocket.accept: (clientsocket, address) = self.serversocket.accept() stackless.tasklet( self.manage)(clientsocket, address) stackless.schedule() def manage(self, clientsocket, address): clientsocket.send( cliensocket.recv(4096)) s = Server((’0.0.0.0’, 8000)) stackless.run()
  • 17. Stackless Example, part II def accept(self): while self.serversocket.accept: (clientsocket, address) = self.serversocket.accept() stackless.tasklet( self.manage)(clientsocket, address) stackless.schedule() def manage(self, clientsocket, address): clientsocket.send( cliensocket.recv(4096)) s = Server((’0.0.0.0’, 8000)) stackless.run()
  • 18. Stackless Example, part II def accept(self): while self.serversocket.accept: (clientsocket, address) = self.serversocket.accept() stackless.tasklet( self.manage)(clientsocket, address) stackless.schedule() def manage(self, clientsocket, address): clientsocket.send( cliensocket.recv(4096)) s = Server((’0.0.0.0’, 8000)) stackless.run()
  • 19. Twisted Built-in solutions Stackless Python 3-rd Party Solutions Kamaelia Summary cogen Others Kamaelia Developed by BBC Research Follows UNIX principles Components all the way round Andrii V. Mishkovskyi Concurrency in Python
  • 20. Kamaelia Example import Axon from Kamaelia.Chassis.ConnectedServer import SimpleServer class Echo(Axon.Component.component): def main(self): while 1: while self.dataReady("inbox"): self.send(self.recv("inbox"), "outbox") yield 1 SimpleServer(protocol=Echo, port=1500).run()
  • 21. Kamaelia Example import Axon from Kamaelia.Chassis.ConnectedServer import SimpleServer class Echo(Axon.Component.component): def main(self): while 1: while self.dataReady("inbox"): self.send(self.recv("inbox"), "outbox") yield 1 SimpleServer(protocol=Echo, port=1500).run()
  • 22. Kamaelia Example import Axon from Kamaelia.Chassis.ConnectedServer import SimpleServer class Echo(Axon.Component.component): def main(self): while 1: while self.dataReady("inbox"): self.send(self.recv("inbox"), "outbox") yield 1 SimpleServer(protocol=Echo, port=1500).run()
  • 23. Kamaelia Example import Axon from Kamaelia.Chassis.ConnectedServer import SimpleServer class Echo(Axon.Component.component): def main(self): while 1: while self.dataReady("inbox"): self.send(self.recv("inbox"), "outbox") yield 1 SimpleServer(protocol=Echo, port=1500).run()
  • 24. Twisted Built-in solutions Stackless Python 3-rd Party Solutions Kamaelia Summary cogen Others cogen Coroutine-based Extensible scheduler Quite low-level (if compared to Kamaelia) Andrii V. Mishkovskyi Concurrency in Python
  • 25. cogen example, part I from cogen.core import sockets from cogen.core import schedulers from cogen.core.coroutines import coroutine @coroutine def server(): srv = sockets.Socket() srv.bind((0.0.0.0’, 8000)) srv.listen(10) while True: conn, addr = yield srv.accept() m.add(handler, args=(conn, addr))
  • 26. cogen example, part I from cogen.core import sockets from cogen.core import schedulers from cogen.core.coroutines import coroutine @coroutine def server(): srv = sockets.Socket() srv.bind((0.0.0.0’, 8000)) srv.listen(10) while True: conn, addr = yield srv.accept() m.add(handler, args=(conn, addr))
  • 27. cogen example, part I from cogen.core import sockets from cogen.core import schedulers from cogen.core.coroutines import coroutine @coroutine def server(): srv = sockets.Socket() srv.bind((0.0.0.0’, 8000)) srv.listen(10) while True: conn, addr = yield srv.accept() m.add(handler, args=(conn, addr))
  • 28. cogen example, part I from cogen.core import sockets from cogen.core import schedulers from cogen.core.coroutines import coroutine @coroutine def server(): srv = sockets.Socket() srv.bind((0.0.0.0’, 8000)) srv.listen(10) while True: conn, addr = yield srv.accept() m.add(handler, args=(conn, addr))
  • 29. cogen example, part II @coroutine def handler(sock, addr): data = yield sock.read() yield sock.write(data) sock.close() return m = schedulers.Scheduler() m.add(server) m.run()
  • 30. cogen example, part II @coroutine def handler(sock, addr): data = yield sock.read() yield sock.write(data) sock.close() return m = schedulers.Scheduler() m.add(server) m.run()
  • 31. cogen example, part II @coroutine def handler(sock, addr): data = yield sock.read() yield sock.write(data) sock.close() return m = schedulers.Scheduler() m.add(server) m.run()
  • 32. cogen example, part II @coroutine def handler(sock, addr): data = yield sock.read() yield sock.write(data) sock.close() return m = schedulers.Scheduler() m.add(server) m.run()
  • 33. Twisted Built-in solutions Stackless Python 3-rd Party Solutions Kamaelia Summary cogen Others Others Concurrence – nice asynchrounous framework with async MySQL driver eventlet – based on coroutines, developed and used by “Second Life” py.execnet – distribute tasks over network Andrii V. Mishkovskyi Concurrency in Python
  • 34. Built-in solutions 3-rd Party Solutions Summary GIL doesn’t harm 90% of the existing code But Twisted, Kamaelia and others are often cleaner Python is not Erlang, it’s better ;) Andrii V. Mishkovskyi Concurrency in Python