Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Coroutine Based Concurrency with PHP and Swoole

Bruce Dou
February 20, 2020

Coroutine Based Concurrency with PHP and Swoole

PHP Swoole has gained traction during the past several years. More and more people are interested with started to try PHP Swoole and use coroutine in PHP to build high performance, large scale web services, online game, micro-services.

Bruce Dou

February 20, 2020
Tweet

More Decks by Bruce Dou

Other Decks in Programming

Transcript

  1. About me • Founder at Transfon • Twitter: @doubaokun •

    Email: [email protected] • Linkedin: linkedin.com/in/brucedou • Github: github.com/doubaokun Twitter: @doubaokun
  2. Agenda • Rethinking about software development • Concurrency, I/O, Scheduling

    and OS • Coroutine: Cooperative multi-tasking • Swoole Coroutine Internal • Swoole • Coroutine and Swoole code samples • Demo Twitter: @doubaokun
  3. Twitter: @doubaokun Mapping real world problems onto machine with several

    levels abstraction with real world limitations in mind
  4. Twitter: @doubaokun 1. 1 CPU cycle 0.3 ns 2. Main

    memory access 120 ns 3. Goroutine 170 ns 4. Swoole Coroutine 190 ns 5. Linux OS context switch 1,000 ns 6. Linux thread launch 5,000 ns 7. Linux process launch 20,000 ns 8. Per-thread stack is 8MB (ulimit -s)
  5. • Unpredictable external performance • Client side I/O • Server

    side I/O • Queue theory Twitter: @doubaokun
  6. Twitter: @doubaokun Mapping real world problems onto machine with several

    levels abstraction with real world limitations in mind about management and structure
  7. Mapping real world to machines: Unlimited Execution Unit and I/O

    vs Limited resources and machines Twitter: @doubaokun
  8. Concurrency models • Process • Process pool • Thread •

    Thread pool • Single thread async I/O • Light weight thread: Fiber / Coroutine / … Twitter: @doubaokun
  9. function add($a, $b) { return $a + $b; } function

    plus5($c, 5) { return add($c, 5); } Twitter: @doubaokun
  10. Light weight Execution Unit provided by machine to map real

    world problems to execute real world tasks Twitter: @doubaokun
  11. “Coroutines are computer components that generalise subroutines for non-preemptive multitasking,

    by allowing execution to be suspended and resumed.” - Wikipedia Twitter: @doubaokun
  12. Twitter: @doubaokun Common pitfalls • Looking to run it on

    M$ Windows • Trying to run it with PHP-FPM • Stateless mind • Variable scope: super global, global, static, local variables • Blocking within Coroutine context • Exception handling • Exit