异步PHP

How does asynchronous programming differ from synchronous programming?

In synchronous programming

  • We issue a statement,
  • We wait for it to complete
  • ..and then move on to the next statement.

In asynchronous programming

  • We issue a statement
  • While we are waiting for it to complete, we can perform other tasks
  • When it has finished, we run a callback function

This means we can reduce total execution time using an asynchronous methodology because we minimize the time spent waiting for operations to complete.

The downside is that often callback depend on callbacks which depend on other callbacks

How can we avoid deeply nested callbacks (Callback Hell)?

  • We don’t have to use callbacks:
  • Promises (or ‘futures’) can help
  • Promises don’t avoid nesting callbacks – they just provide a nicer syntax to deal with them

What is the difference between multi-threading and asynchronous programming?

  • Usually asynchronous code/languages will use threads
  • This is an implementation detail which is abstracted from the user
  • Usually in asynchronous code, all of the core application logic takes place in one thread
  • Other threads are usually ‘lightweight’ and are just waiting for some blocking/IO code to complete
  • In true multithreaded programming, core program logic will be executed in many threads

Introducing Asynchronous concepts into PHP

  • This is unlike the ‘traditional’ implementation/libraries we are used to in PHP
  • We can use multi-threading in PHP using the pthreads extension
  • This requires Zend Thread Safety
  • Threads are not necessary for concurrent execution in PHP – Process Control Extensions use process forking
  • If we are to write PHP asynchronously, this rules out use of a lot of functions/libraries we like to use, because they block on IO
  • These problems are not unique to PHP

Libraries for writing async PHP

  • Icicle
  • React PHP
  • On a simple level, it is possible to write asynchronous PHP code by spawning additional processes using exec – you don’t need a library

A PSR for async in PHP

PHP 5.5 introduces Generators and the yield keyword – do these help us to use asynchronous techniques in PHP?

  • Icicle makes use of this heavily
  • This allows us to write asynchronous code that looks more like synchronous code
  • We may see an implementation of async/await in PHP in future, but not soon
  • This is similar to the path that NodeJS and Python have followed or are following
  • This will require non-blocking versions of existing blocking functions like file_get_contents() to be written, but this process is underway
异步PHP
标签:     

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*