drupal的锁(lock)机制

         不少时候咱们会遇到多我的在同时操做一篇文章,一个变量等状况,给我带来了很多麻烦。好比你刚修改完一篇文章,另一个也在修改这篇文章致使你刚修改的就被覆盖了,我相信也不是你想要的结果。下面我讲一下drupal对同时操做一个变量的锁机制php

        在drupal初始化的时候会从表cache_bootstrap取drupal的一些配置variables这个键对应的键值里面存储着drupal全部的配置(经过admin/config配置通常都在这个里面)在初始化的时候用到了锁机制。大致讲一下流程:bootstrap

function variable_initialize($conf = array()) {
  // NOTE: caching the variables improves performance by 20% when serving
  // cached pages.
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
    $variables = $cached->data;
  }
  else {
    // Cache miss. Avoid a stampede.
    $name = 'variable_init';
    #这个地方用到了锁机制 lock_acquire($name, 1)运用这个方法主动去锁。去取variables是判断表semaphore是否存在键variable_init 若是存在去更新有效期 这个地方我分析了一下返回false的状况只有一种就是插入失败的时候
    插入失败就是意味者有其余人在操做着variables,由于semaphore表name是惟一的不能插入两遍。若是没有人同时进行操做返回应该是ture 那就走下面的代码了 另外正常状况下你主动锁一个键后 当程序执行完后会自动删除由于注册了方法
    drupal_register_shutdown_function('lock_release_all', $lock_id);
    if (!lock_acquire($name, 1)) {
      // Another request is building the variable cache.
      // Wait, then re-run this function.
      lock_wait($name);
      return variable_initialize($conf);
    }
    else {
      // Proceed with variable rebuild.
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
      cache_set('variables', $variables, 'cache_bootstrap');
      lock_release($name);
    }
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

  return $variables;
}
相关文章
相关标签/搜索