簡體   English   中英

每次使用帶有 LOCK_EX 標志的 LOCK_NB 時,相同的程序/進程都獲取鎖

[英]Same program/process acquiring lock every time when using LOCK_NB with LOCK_EX flag

我有一個要求,其中兩個單獨的進程/程序並行運行(一個用Python編寫,一個用C++編寫)需要獲得獨占訪問權限,修改硬件相關值。

我正在嘗試使用flock來實現它們之間的同步。

相同的代碼如下,

Python代碼

#!/usr/bin/python

import fcntl
import time
import datetime
import os

SLICE_SLEEP = 5
LOCK_HOLD_TIME = 20
TOTAL_WAIT_TIME = 300

class LockUtil(object):
   FILE_PATH = "/tmp/sync.lock"
   fd = -1

   @staticmethod
   def acquireLock(totalWaitTime=TOTAL_WAIT_TIME):
      try:
         LockUtil.fd = os.open(LockUtil.FILE_PATH,os.O_WRONLY|os.O_CREAT)
         print('Trying to acquire lock')
         retryTimes = (totalWaitTime/SLICE_SLEEP)
         currentCounter = 0
         while currentCounter < retryTimes:
            try:
                fcntl.flock(LockUtil.fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
                print('Lock acquired successfully')
                return
            except IOError:
                print('Failed to acquire the lock, sleeping for {} secs'.format(SLICE_SLEEP))
                time.sleep(SLICE_SLEEP)
                currentCounter += 1
         print('Tried {} times, now returning'.format(retryTimes))
      except IOError:
         print('Can not access file at path: {}'.format(FILE_PATH))

   @staticmethod
   def releaseLock():
      fcntl.flock(LockUtil.fd,fcntl.LOCK_UN)
      print('Lock released successfully')

class LockHelper(object):
   def __init__(self):
      LockUtil.acquireLock()
   def __del__(self):
      LockUtil.releaseLock()

def createObjAndSleep():
   lock = LockHelper()
   time.sleep(LOCK_HOLD_TIME)

def main():
   while True:
      createObjAndSleep()

if __name__ == '__main__':
   main()

C++代碼

#include <iostream>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/file.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <ctime>
#include <memory>

int SLICE_SLEEP = 6;
int LOCK_HOLD_TIME = 20;
int TOTAL_WAIT_TIME = 300;
int SUCCESS = 0;

class LockUtil {
   public:
      static std::string path;
      static int fd;
      static int acquireLock(int totalWaitTime=TOTAL_WAIT_TIME);
      static int releaseLock();
};

std::string LockUtil::path = "/tmp/sync.lock";
int LockUtil::fd = -1;

int LockUtil::acquireLock(int totalWaitTime) {
   fd = open(path.c_str(), O_WRONLY|O_CREAT, 0666);
   if(fd != -1)
   {
      auto retryTimes = (totalWaitTime/SLICE_SLEEP);
      auto currentCounter = 0;
      while(currentCounter < retryTimes)
      {
        std::cout << "Trying to acquire lock" << std::endl;
        auto lockStatus = flock(fd,LOCK_EX|LOCK_NB);
        if(lockStatus == SUCCESS)
        {
            std::cout << "Lock acquired successfully" << std::endl;
            return 0;
        } else {
            std::cout << "Failed to acquire the lock, sleeping for " << SLICE_SLEEP << " secs" << std::endl;
            sleep(SLICE_SLEEP);
            currentCounter += 1;
        }
      }
   } else {
      std::cout << "Unable to open the file!" << std::endl;
      std::cout << strerror(errno) << std::endl;
      return -1;
   }
}

int LockUtil::releaseLock() {
   if(fd != -1)
   {
      flock(fd,LOCK_UN);
      std::cout << "Lock released successfully" <<  std::endl;
      return 0;
   } else {
      return -1;
   }
}

class LockHelper {
   public:
      LockHelper() {
         LockUtil::acquireLock();
      }
      ~LockHelper() {
         LockUtil::releaseLock();
      }
};

void createObjAndSleep()
{
   std::unique_ptr<LockHelper> lockObj(new LockHelper());
   sleep(LOCK_HOLD_TIME);
}

int main(void) {
   while (true) {
      createObjAndSleep();
   }
}

但是,當我並行運行這兩個程序時,可以觀察到首先獲得文件鎖的進程一直在獲得它,而另一個進程則處於飢餓狀態。

但是,如果我將兩個程序中的標志更改為僅使用LOCK_EX並刪除LOCK_NB ,則鎖將以循環方式在進程之間共享。

我想了解使用LOCK_NB標志時程序中的錯誤是什么。

操作系統

unname -a

Linux 0000000000002203 4.4.43-hypriotos-v7+ #1 SMP PREEMPT Thu Jan 19 20:54:06 UTC 2017 armv7l GNU/Linux

Python 版本 - 2.7

C++ 版本 - C++11

我不認為這本身就是一個錯誤,但可能是一個意想不到的后果。 當你使用阻塞的flock時,你的進程被放入內部的Linux kernel隊列,一旦鎖被釋放,這個隊列就會喚醒進程。

雖然 Linux 群不能保證公平調度,但看起來事件序列或多或少地公平調度分配鎖定。

另一方面,使用非阻塞鎖,您的進程會不斷嘗試鎖定它。 結果,沒有鎖隊列,取而代之的是,有進程不斷地實時競爭鎖。 為了實現這種鎖定,當鎖定可用時,進程需要在 cpu 上運行,而調度程序似乎只是沒有給進程在此時存在的機會。

調度策略非常復雜,所以我不會推測究竟是什么導致了這種調度器行為。

最后但同樣重要的是,當涉及到非阻塞鎖時,您的最終目標是什么? 你為什么要他們?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM