Skip to content

Instantly share code, notes, and snippets.

@ncode
Created August 22, 2010 02:40
Show Gist options
  • Save ncode/543207 to your computer and use it in GitHub Desktop.
Save ncode/543207 to your computer and use it in GitHub Desktop.
class shared_dict():
def __init__(self):
self.values = dict().copy()
self.shmem = mmap.mmap(-1, 40000, mmap.MAP_SHARED)
self.lock = mmap.mmap(-1, 1024, mmap.MAP_SHARED|mmap.MAP_ANONYMOUS)
def save(self):
self.__lock()
self.shmem.seek(0)
try:
cache = pickle.loads(self.shmem.read(-1))
self.values.update(cache.items() + self.values.items())
except EOFError:
pass
self.shmem.seek(0)
self.shmem.write(pickle.dumps(self.values))
self.__unlock()
def reload(self):
self.shmem.seek(0)
cache = pickle.loads(self.shmem.read(-1))
self.values.update(cache.items() + self.values.items())
def __lock(self):
while True:
self.lock.seek(0)
if self.lock[0] == chr(1):
sleep(0.1)
else:
self.lock[0] = chr(1)
break
return True
def __unlock(self):
self.lock[0] = chr(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment