Skip to content

Instantly share code, notes, and snippets.

@krakjoe
Created February 26, 2014 17:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krakjoe/9233917 to your computer and use it in GitHub Desktop.
Save krakjoe/9233917 to your computer and use it in GitHub Desktop.
using workers
<?php
define("SECOND", 1000000);
class Task extends Stackable {
public function run() {
/* some random data */
$this->data = md5(
mt_rand() * microtime());
}
}
class Background extends Worker {
public function run() {}
}
$tasks = [];
/* this allows you to get the next free slot and stack
a job in that slot while processing the data the previous
task in that slot generated */
function get_next_task($tasks, &$done) {
foreach ($tasks as $id => $task ){
if ($task->data) {
$done = $task;
return $id;
}
}
return count($tasks);
}
$background = new Background();
$background->start();
do {
$next = get_next_task($tasks, $done);
$tasks[$next] = new Task();
$background
->stack($tasks[$next]);
/* got something to deal with */
if ($done)
var_dump($done->data);
} while(1);
?>
@krakjoe
Copy link
Author

krakjoe commented Feb 26, 2014

Note that, because it takes no time at all to var_dump data, eventually you might run out of memory if you run this for a long long time, because the size of $tasks keeps growing ...

The idea of using something like get_next_stack is explained, but you need not do it this way, so long as you retain references to stacked tasks for as long as they are executing, you can make up your own way of managing the list of tasks ...

@mrsimonbennett
Copy link

Thank you I will have play with this later.

Here is props the best place for me to explain what I am am trying to do.

I am creating a web server so I have played with single loop and the socket select these work well as single threaded options.

I have also tired the fire a thread per client which works but not well especially if you pass the socket to the thread, ( we did talk about this on krakjoe/pthreads#192)

So the plan was to fire up a pool of threads pass them the request variables (not the socket) process the request and then read the response from the thread when its finished. The main thread that handels the sockets will use the socket select so will not be IO bound to the socket.

So the thread needs to run, be checked to see ifs its done, if its done the response and pull the data out and the return it to the thread pool as a free thread for work. This might not be perfect but sounds a lot better than a thread per connection.

Thanks for your help so far :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment