每次使用带有LOCK_EX标志的LOCK_NB时,相同的程序/进程都会获取锁
Same program/process acquiring lock every time when using LOCK_NB with LOCK_EX flag
我有一个要求,其中两个并行运行的独立进程/程序(一个用Python编写,一个用C++编写(需要获得独占访问权限,修改与硬件相关的值。
我正在尝试使用羊群在它们之间实现同步。
相同的代码如下,
蟒蛇代码
#!/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标志时程序中的错误是什么。
操作系统
uname -a
Linux0000000000002203 4.4.43-hypriotos-v7+ #1 SMP 抢占 周四 1月 19 日 20:54:06 UTC 2017 armv7l GNU/Linux
蟒蛇版本 - 2.7
C++版本 - C++11
我不认为这本身是一个错误,但可能是一个意想不到的后果。当您使用阻塞flock
时,您的进程被放入内部 Linux 内核队列中,该队列应在释放锁后唤醒该进程。
虽然 Linux flock 不能保证公平的调度,但看起来事件的顺序或多或少地将锁定分配在公平的调度中。
另一方面,使用非阻塞锁定,您的进程会不断尝试锁定它。因此,没有锁定队列,相反,有些进程不断实时竞争锁定。为了实现此锁定,当锁定可用时,进程需要在 CPU 上,并且调度程序似乎此时没有给进程机会。
调度策略非常复杂,所以我不会推测究竟是什么导致了这种调度程序行为。
最后但并非最不重要的一点是,在非阻塞锁方面,您的最终目标是什么?你为什么想要它们?
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址