Last active
August 31, 2021 09:37
-
-
Save haolian9/29309fed88c41eadf173b9381cb7cbe5 to your computer and use it in GitHub Desktop.
ensure no race condition in swoole coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Swoole\Coroutine::enableScheduler(); | |
Co\run(function () { | |
$flag = 1; | |
go(function() use(&$flag) { | |
assert($flag == 1); | |
$flag += 1; | |
assert($flag == 2); | |
}); | |
go(function() use(&$flag) { | |
# let co#1 run first | |
Co::sleep(0.3); | |
assert($flag == 2); | |
$flag += 1; | |
assert($flag == 3); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function syscall(int $arg) { | |
# simulate overhead for invoking syscall | |
Co::sleep(0.3); | |
return $arg + 1; | |
} | |
function debug(int $id) { | |
return function (string $format, ... $args) use ($id) { | |
# TODO@haoliang ensure printf which writes to stdout/stderr will not yield | |
printf("[co#%d] {$format}\n", $id, ...$args); | |
}; | |
} | |
Co\run(function () { | |
$flag = 1; | |
go(function() use (&$flag) { | |
$debug = debug(1); | |
$debug("entered"); | |
assert($flag == 1); | |
$flag += 1; | |
assert($flag == 2); | |
$debug("invoking a syscall"); | |
$result = syscall($flag); | |
$debug("got syscall result"); | |
assert($result == 3); | |
$debug("exiting"); | |
}); | |
go(function() use(&$flag) { | |
$debug = debug(2); | |
$debug("entered"); | |
Co::sleep(0.1); | |
$debug("re-entered"); | |
assert($flag == 2); | |
$flag += 1; | |
assert($flag == 3); | |
$debug("exiting"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment