两道面试题

#1.多进程写文件
function write_file($filename, $content)
{
    $lock = $filename . '.lck';
    $write_length = 0;
    while(true) {
        if( file_exists($lock) ) {
            usleep(100);
        } else {
            touch($lock);
            $write_length = file_put_contents($filename, $content, FILE_APPEND);
            break;
        }
    }
    if( file_exists($lock) ) {
        unlink($lock);
    }
    return $write_length;
}

----------------------------------------------------------------------------------------------
#2.双向队列

class DEQueue {
    //存储
    protected $_storage = array();
    
    //入头
    public function unshift($element)
    {
        return array_unshift($this->_storage, $element);
    }
    
    //入尾
    public function push($element)
    {
        return array_push($this->_storage, $element);
    }
    
    //出尾
    public function pop()
    {
        return array_pop($this->_storage);
    }
    
    //出头
    public function shift()
    {
        return array_shift($this->_storage);
    }
    
    //长度
    public function length()
    {
        return count($this->_storage);
    }
}

你可能感兴趣的:(两道面试题)