Skip to content

Instantly share code, notes, and snippets.

@sgolemon
Last active December 15, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgolemon/5279803 to your computer and use it in GitHub Desktop.
Save sgolemon/5279803 to your computer and use it in GitHub Desktop.
Current rough outline of AsyncThread's API. (work in progress) If it works as well as I hope it does, expect a repo with an extension implementing it.
<?php
if (empty($_SESSION['threadName'])) {
$t = new AsyncThread("util/handler.php");
// By setting a name, it becomes persistent and may be resumed later
$t->setName($_SESSION['threadName'] = uniqid());
} else {
// Previously started AsyncThread instance with still-running script
$t = AsyncThread::Resume($_SESSION['threadName']);
}
$t->recvMessageSetBlocking(true);
$t->recvMessageSetPeek(false);
// Thread $t is running concurrently with main request
// Messages can be pushed in with sendMessage($code, $message = null)
$t->sendMessage(ADD_NUMBERS, array(1, 2));
// And popped out with one of:
// recvMessage()
// recvMessageRange($minCode, $maxCode)
// recvMessageCodes(Array $codes)
list($code, $message) = $t->recvMessage();
if ($code == TOTAL) {
echo "The other thread says our total is $message\n";
}
?>
In util/handler.php (the script we setup to run in an async thread:
<?php
$t = AsyncThread::Self();
$t->recvMessageSetBlocking(true);
$t->recvMessageSetPeek(false);
// Messages send by the request process are received inside the async thread
// The same way the request thread receives messages from us:
for(;;) {
list($code, $message) = $t->recvMessage();
switch($code) {
case ADD_NUMBERS:
$result = array_sum($message);
$t->sendMessage(TOTAL, $result);
break;
}
}
?>
ADD_NUMBERS and TOTALS are app defined message codes such as:
<?php
define('ADD_NUMBERS', 1);
define('TOTAL', 2);
?>
In practice, you'd probably subclass AsyncThread to provide helper functions for sending and receiving the messages in a way that makes sense to your app. Probably building your handler loop into that class as well.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment