I am trying to create a counter using shared block memory, just look at the code:
$i=0; $counter = new counter('g'); while($i<3){ $pid = pcntl_fork(); echo $counter->get()."\t".$i."\t".$pid."\n"; $i++; } class counter { protected static $projID = array(); protected $t_key; protected $length; function __construct($projID){ !in_array( $projID, self::$projID) or die('Using duplicate project identifer "'.$projID.'" for creating counter'); self::$projID[] = $projID; $this->t_key = ftok(__FILE__, $projID); $this->shmid = shmop_open($t_key, 'c', 0755, 64); $this->length = shmop_write($this->shmid, 0, 0); shmop_close($this->shmid); } function get(){ $sem = sem_get($this->t_key, 1); sem_acquire($sem); $shmid = shmop_open($this->t_key, 'c', 0755, 64); $inc = shmop_read($shmid, 0, $this->length); $this->length = shmop_write($shmid, $inc+1, 0); shmop_close($shmid); sem_release($sem); return $inc; } }
But il will get a strange result
7 0 2567 8 1 2568 9 0 0 1 1 0 2 2 2569 40 1 2570 4 2 2572 3 2 0 51 2 2571 52 1 0 63 2 0 5 2 0 64 2 2573 65 2 0
I want to create this class to read and write lines in a file in multithreading.
source share