OpenSwoole\Coroutine::create

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Coroutine::create(callable $callback, ...$params): int|false

Parameters

callback

The function will be executed within the coroutine.

params

The array of params of the callback function

Return

Description

Create and execute the closure function in a coroutine. A coroutine is a light weight thread running within a Linux process.

Go can be used to create new coroutine which is the short name of OpenSwoole\Coroutine::create. Co is the short name of OpenSwoole\Coroutine.

Coroutines must be executed within a coroutine context.

co::run can be used to create a context to execute coroutines.

A coroutine context is created for each callback function of OpenSwoole Server.

Since version 4.1.0, you can use any IO libraries using php_stream within a coroutine context.

Since version 4.7.0, Coroutine\go() and OpenSwoole\Coroutine::create returns the ID of the created coroutine.

Supported libraries:

  • Redis
  • mysqlnd, PDO, mysqli
  • SOAP
  • file_get_contents, fopen
  • stream_socket_client
  • fsockopen
  • curl
  • fread, fwrite, fgets

Not supported:

  • MySQL with libmysqlclient
  • curl with libcurl
  • MongoDB with mongo-c-client
  • pdo_pgsql, pdo_ori, pdo_odbc, pdo_firebird

Coroutine execution order

Mutliple corotuines created with go are executed concurrently.

<?php
co::run(function() {
    go(function () {
        co::sleep(3);
        go(function () {
            co::sleep(2);
            echo "co[3] end\n";
        });
        echo "co[2] end\n";
    });

    co::sleep(1);
    echo "co[1] end\n";
});

Coroutine execution cost

Each coroutine use 8KB memory stack to store variables by default in PHP 7.2+.

Example

<?php
co::run(function () {
    co::usleep(500000);
    echo "hello";
    go("test");
    go([$object, "method"]);
});
Last updated on September 1, 2022