Implement flock locking.

This commit is contained in:
Quantum 2017-11-19 02:17:31 -05:00
parent eb3f804ce5
commit 9689c11b36
2 changed files with 30 additions and 21 deletions

View file

@ -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: try:
import msvcrt import msvcrt
except ImportError: except ImportError:
# Currently no linux solution with fcntl. import fcntl
raise RuntimeError('Linux locker not written yet.') import os
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
class FileLock(FileLockBase):
def acquire(self, blocking=True): 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): 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): def release(self):
self.acquire() msvcrt.locking(self.fd, msvcrt.LK_UNLCK, -1)
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()

View file

@ -1,5 +1,3 @@
"""Defines the Game manager."""
import os import os
import errno import errno
import itertools import itertools