我有一个需求,其中两个独立的并行运行的进程/程序(一个用Python编写,一个用C++编写)需要获得独占访问,修改一个硬件相关的值。
我正在尝试使用flock实现它们之间的同步。
代码如下所示,
#!/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()
#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标志时,程序中的bug是什么。
uname-a
Linux 0000000000002203 4.4.43-Hypriotos-V7+#1 SMP抢占Thu Jan 19 20:54:06 UTC 2017 armv7l GNU/Linux
Python版本-2.7
C++版本-C++11
我不认为这是一个错误本身,但可能是一个意外的后果。 当您使用阻塞flock
时,您的进程被放入内部Linux内核队列中,一旦锁被释放,该队列将唤醒进程。
虽然Linux flock没有公平调度的保证,但它看起来像是事件序列在或多或少的公平调度中分配锁定。
另一方面,使用非阻塞锁,您的进程会不断尝试锁定它。 因此,不存在锁队列,相反,存在不断地实时竞争锁的进程。 为了实现这种锁,进程需要在锁可用时处于-CPU上,而调度程序似乎只是不给进程在此时处于那里的机会。
调度策略是极其复杂的,所以我不会去推测到底是什么导致了这个调度器的行为。
最后但并非最不重要的是,当涉及到非阻塞锁时,您的最终目标是什么? 你为什么要他们?