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;
}
相關文章
相關標籤/搜索