/* * Sequence number generator. */ Class Seqgenerator { Const SHM_KEY = 1; /** * Initialization of Sequence number generator. * Only the first call after server startup is valid, and calling this method after this does not actually work. * @param int $start The starting value of the sequence number. * @return Boolean returns true to indicate success. */ static public function init ($start = 1) { Mutual exclusion through semaphores to avoid access violation of shared memory $SW = new Semwrapper; if (! $SW->acquire ()) { return false; } Open Shared Memory $shm _id = Shmop_open (Self::shm_key, ' n ', 0644, 4); if (Empty ($shm _id)) { Because the ' n ' mode is used, if shared memory cannot be opened, you can assume that the shared memory has been created without having to initialize it again $SW->release (); return true; } Write an initial value in shared memory $size = Shmop_write ($shm _id, pack (' L ', $start), 0); if ($size! = 4) { Shmop_close ($shm _id); $SW->release (); return false; } Turn off shared memory, release semaphores Shmop_close ($shm _id); $SW->release (); return true; } /** * Generate the next order number. * Order number generated by @return int */ static public Function Next () { Mutual exclusion through semaphores to avoid access violation of shared memory $SW = new Semwrapper; if (! $SW->acquire ()) { return 0; } Open Shared Memory $shm _id = Shmop_open (Self::shm_key, ' W ', 0, 0); if (Empty ($shm _id)) { $SW->release (); return 0; } To read a sequential number from shared memory $data = Shmop_read ($shm _id, 0, 4); if (empty ($data)) { $SW->release (); return 0; } $arr = Unpack (' L ', $data); $seq = $arr [1]; Write the next sequential number to shared memory $size = Shmop_write ($shm _id, pack (' L ', $seq + 1), 0); if ($size! = 4) { $SW->release (); return 0; } Turn off shared memory, release semaphores Shmop_close ($shm _id); $SW->release (); return $seq; } } |