Dudek 141 a simple lock solution import os time

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: # do whatever must be done f = open(key, "w") f.write(data) # write new data f.close() # (could delete the file instead if updated data is empty) CS 206 G. Dudek 138 (G)DBM files # better performance if there are many records import gdbm im gdbm key = ...username, or session key, or whatever... db = gdbm.open("DATABASE", "w") # open for reading+writing db gdbm if db.has_key(key): data = db[key] # read previous data else: data = "" # provide initial data data = update(data, form) db[key] = data # write new data db.close() CS 206 G. Dudek 139 Shelves # a shelf is a (g)dbm files that stores pickled Python objects dbm pickled import shelve class UserData: ... class UserData key = ...username, or session key, or whatever... db = shelve.open("DATABASE", "w") # open for reading+writing db shelve if db.has_key(key): data = db[key] # an object! else: data = UserData(key) UserData # create a new instance data.update(form) db[key] = data db.close() CS 206 G. Dudek 140 Locking • (G)DBM files and shelves are not protected against concurrent updates! • Multiple readers, single writer usually OK – simplest approach: only lock when writing • Good filesystem-based locking is hard file -ba – no cross-platform solutions – unpleasant facts of life: » » » processes sometimes die without unlocking processes sometimes take longer than expected NFS semantics CS 206 G. Dudek 141 A simple lock solution import os, time import os def unlock(self): assert self.locked class Lock: self.locked = 0 os.rmdir(self.filename) os def __init__(self, filename): self.filename = filename # auto-unlock when lock object is deleted self.locked = 0 def __del__(self): if self.locked: def lock(self): self.unlock() assert not self.locked while 1: try: # for a big production with timeouts, os.mkdir(self.filename) os # see the Mailman source code (LockFile.py); self.locked = 1 # it works on all Unixes and supports NFS; and return except os.error, err:...
View Full Document

Ask a homework question - tutors are online