From 9689c11b3624a7f6e235d411953e5a4b7bc0c454 Mon Sep 17 00:00:00 2001 From: Quantum Date: Sun, 19 Nov 2017 02:17:31 -0500 Subject: [PATCH] Implement flock locking. --- _2048/lock.py | 49 +++++++++++++++++++++++++++++------------------- _2048/manager.py | 2 -- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/_2048/lock.py b/_2048/lock.py index b51e64f..865d502 100644 --- a/_2048/lock.py +++ b/_2048/lock.py @@ -1,28 +1,39 @@ -"""An implementation of a file locker.""" +class FileLockBase(object): + def __init__(self, fd): + if hasattr(fd, 'fileno') and callable(fd.fileno): + self.fd = fd.fileno() + else: + self.fd = fd + + def acquire(self, blocking=True): + raise NotImplementedError() + + def release(self): + raise NotImplementedError() + + def __enter__(self): + self.acquire() + + def __exit__(self, exc_type, exc_val, exc_tb): + self.release() + -# Import msvcrt if possible. try: import msvcrt except ImportError: - # Currently no linux solution with fcntl. - raise RuntimeError('Linux locker not written yet.') -else: - class FileLock(object): - def __init__(self, fd, size=65536): - if hasattr(fd, 'fileno') and callable(fd.fileno): - self.fd = fd.fileno() - else: - self.fd = fd - self.size = size + import fcntl + import os + class FileLock(FileLockBase): def acquire(self, blocking=True): - msvcrt.locking(self.fd, (msvcrt.LK_NBLCK, msvcrt.LK_LOCK)[blocking], self.size) + fcntl.flock(self.fd, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB)) def release(self): - msvcrt.locking(self.fd, msvcrt.LK_UNLCK, self.size) + fcntl.flock(self.fd, fcntl.LOCK_UN) +else: + class FileLock(FileLockBase): + def acquire(self, blocking=True): + msvcrt.locking(self.fd, (msvcrt.LK_NBLCK, msvcrt.LK_LOCK)[blocking], -1) - def __enter__(self): - self.acquire() - - def __exit__(self, exc_type, exc_val, exc_tb): - self.release() + def release(self): + msvcrt.locking(self.fd, msvcrt.LK_UNLCK, -1) diff --git a/_2048/manager.py b/_2048/manager.py index 4462297..e4982d5 100644 --- a/_2048/manager.py +++ b/_2048/manager.py @@ -1,5 +1,3 @@ -"""Defines the Game manager.""" - import os import errno import itertools