How do you generate random unique identifiers in a multi process and multi thread environment?
问题 Every solution I come up with is not thread save. def uuid(cls,db): u = hexlify(os.urandom(8)).decode('ascii') db.execute('SELECT sid FROM sessions WHERE sid=?',(u,)) if db.fetch(): u=cls.uuid(db) else: db.execute('INSERT INTO sessions (sid) VALUES (?)',(u,)) return u 回答1: Your algorithm is OK (thread safe as far as your DB API module is safe) and probably is the best way to go. It will never give you duplicate (assuming you have PRIMARY or UNIQUE key on sid), but you have a neglectfully