Coroutine System API

The Coroutine System provides a group of helper functions that can be used within a coroutine context, these methods do not block your program, they run asynchronously. Calling any of the methods below will result in some coroutine switching to happen, Swoole will automatically switch to execute another coroutine while waiting for IO, this is known as coroutine scheduling.

In other words, functions such as sleep() provided by PHP should not be used within the coroutine context unless you enable coroutine hooks, otherwise the process will be blocked. Checkout the sleep hook.

The functions fread(), fwrite() and fgets() can be used within the coroutine context and not blocking the process when you enable coroutine hooks so using the below methods for the equivalent functions (read & write) is not recommended if you can use hooks instead. Checkout the file hook.

As already mentioned a lot of the functions here are made redundant due to coroutine hooks, please read the documentation there to understand which API is best for your situation. Hooks basically allow Swoole to take control of existing functions and execute them in a coroutine safe manner, this is what achieves high concurrency without having to do much or learn a lot more new API.

Available since version 4.4.6

Coroutine System Namespace Usage

Before version v4.4.6 the coroutine system functions were using Swoole\Coroutine or the shorthand Co. Since version v4.4.6 the coroutine system API has been moved to a new namespace Swoole\Coroutine\System and the shorthand changed to Co\System. Both the old style naming have been kept for backwards compatibility but may be removed in the future.

Please convert and use either Co\System or Swoole\Coroutine\System.

For example the following converts over to:

  • Co::sleep(5) becomes Co\System::sleep(5)
  • Swoole\Coroutine::sleep(5) becomes Swoole\Coroutine\System::sleep(5)

Remember that Co\System is just a shorthand for the full namespace.


Client Timeouts

All network requests (establish a connection, send data and receive data) may time out. Some of the methods within the Co\System API have a few ways for how you can setup timeouts.

Timeouts can be set by either using the function parameter or by using the coroutine configuration method, refer to the timeout guide to understand how to setup timeouts.