Coroutine function

The framework encapsulates some functions of the coroutine operation, which is convenient for developers to call.

Create a coroutine

In the Swoft framework, you must not use the `go` function provided by Swoole to create a coroutine. Otherwise, the request and context will be lost, causing some strange problems.

 use Swoft\Co;

Co::create(function(){
    // to do
}); 

The above is the prototype of the coroutine created in the framework, the framework also provides a simpler sgo function to create a coroutine, replacing the Swoole's go function.

 sgo(function(){
    // todo
}); 

The `sgo` function is exactly the same as the Swoole `go` function. Remember that the `sgo` function can only be used in the framework. You can't use the `go` function directly.

Coroutine ID

Get current coroutine ID, -1 non-co-process environment

 use Swoft\Co;

$id = Co::id(); 

Top coroutine ID

Get the top level (the outermost coroutine ID)

 use Swoft\Co;

$id = Co::tid(); 

Read file

Read the file in full

 public static function readFile(string $filename): string 
  • File path read

The read successfully returns the contents of the string. If the read fails, it returns false. You can use swoole_last_error to get the error message. The readFile method has no size limit, and the read content will be stored in memory, so it may take up too much memory when reading a very large file.

Use example:

 use Swoft\Co;

$fileName = 'test.file';
$data = Co::readFile($fileName); 

Write file

 public static function writeFile(string $filename, string $data, int $flags = null): int 
  • Filename is the name of the file. It must have writable permissions. If the file does not exist, it will be created automatically. Failed to open the file will immediately return false
  • $fileContent is the content to be written to the file, up to 4M
  • Flags is the option to write. By default, the current file content will be cleared. You can use FILE_APPEND to append to the end of the file.

Write success returns true, write failure returns false

 use Swoft\Co;

$fileName = 'test.file';
$data = Co::writeFile($fileName, 'data'); 

Concurrent

The bottom layer of the framework encapsulates a set of multi-hybrid IO concurrent operations through the coroutine channel. Generally, it is used for multiple processes without dependencies, and can be executed concurrently to improve execution efficiency.

 public static function multi(array $requests, float $timeout = 0): array 
  • Requests multiple operations collection, KV array format
  • Timeout timeout, default permanent timeout

The result of the concurrent execution is returned according to the key relationship of the requests collection array. If the value corresponding to a key returns false, it means that the operation fails. The operation of each operation in the requests has no upper limit, depending on the business.

The requests format supports multiple ways

  • a method of an object
  • Static method of the object
  • Closure anonymous function

The use examples are as follows:

 use Swoft\Co;

/**
 * Class CoTest
 *
 * @since 2.0
 */
class CoTest
{
    /**
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     */
    public function testMulti()
    {
        $requests = [
            'method'       => [$this, 'requestMethod'],
            'staticMethod' => "SwoftTest\Unit\CoTest::requestMehtodByStatic",
            'closure'      => function () {
                $cli = new Client('www.baidu.com', 80);
                $cli->get('/');
                $result = $cli->body;
                $cli->close();

                return $result;
            }
        ];

        $response = Co::multi($requests);
    }

    /**
     * @return mixed
     */
    public function requestMethod()
    {
        $cli = new Client('www.baidu.com', 80);
        $cli->get('/');
        $result = $cli->body;
        $cli->close();

        return $result;
    }

    /**
     * @return mixed
     */
    public static function requestMehtodByStatic()
    {
        $cli = new Client('www.baidu.com', 80);
        $cli->get('/');
        $result = $cli->body;
        $cli->close();

        return $result;
    }
} 
/docs/2.x/en/common/co.html
progress-bar