Skip to content

Instantly share code, notes, and snippets.

@krakjoe
Created February 27, 2013 18:37
Show Gist options
  • Select an option

  • Save krakjoe/5050370 to your computer and use it in GitHub Desktop.

Select an option

Save krakjoe/5050370 to your computer and use it in GitHub Desktop.
editable configuration originating from APC by example...
<?php
/*
An example of read/writable multi-threaded configuration
*/
class Config extends Stackable {
public function __construct($config) {
$this->map($config);
}
/* this makes everything safe */
/* anything that was an array will be turned into stackable data */
/* stackables can be referrenced as if they implement ArrayAccess
so it does not affect any code already using the configuration array */
public function map($c) {
foreach ($c as $k => $v) {
if (is_array($v)) {
$this[$k]=new Config($v);
} else $this->$k = $v;
}
}
public function run(){
/* possibly stack this on a worker thread to affect subsequent processes with up-to-date configuration data */
}
}
/* take a config object and an id */
class My extends Thread {
public function __construct($config, $id) {
$this->config = $config;
$this->id = $id;
}
/* edits the configuration if the id is even */
public function run() {
if (($this->id) % 2 == 0) {
$this->config[$this->id]=mt_rand(
$this->id, $this->id*100);
}
}
}
ini_set("apc.enable_cli", 1);
/* from a previous request */
apc_store("config", array(
"config" => "data",
"some" => array(
"nested" => "config"
)
));
/* configuration can originate from APC in this thread just fine */
$config = new Config(apc_fetch("config"));
/* show */
var_dump($config);
/* the threads with an even id will edit the configuration and affect all contexts */
$threads = array();
while (++$i < 50) {
$threads[$i]=new My($config, $i);
$threads[$i]->start();
}
/* join to show */
foreach($threads as $thread)
$thread->join();
/* same reference, any reference would do */
var_dump($config);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment