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):
# 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): if hasattr(fd, 'fileno') and callable(fd.fileno):
self.fd = fd.fileno() self.fd = fd.fileno()
else: else:
self.fd = fd self.fd = fd
self.size = size
def acquire(self, blocking=True): def acquire(self, blocking=True):
msvcrt.locking(self.fd, (msvcrt.LK_NBLCK, msvcrt.LK_LOCK)[blocking], self.size) raise NotImplementedError()
def release(self): def release(self):
msvcrt.locking(self.fd, msvcrt.LK_UNLCK, self.size) raise NotImplementedError()
def __enter__(self): def __enter__(self):
self.acquire() self.acquire()
def __exit__(self, exc_type, exc_val, exc_tb): def __exit__(self, exc_type, exc_val, exc_tb):
self.release() self.release()
try:
import msvcrt
except ImportError:
import fcntl
import os
class FileLock(FileLockBase):
def acquire(self, blocking=True):
fcntl.flock(self.fd, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))
def release(self):
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 release(self):
msvcrt.locking(self.fd, msvcrt.LK_UNLCK, -1)

View file

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