Python beginner. I have a class as follows, which maintains simple dictionary for historical records. It needs to support insertion of records and lookup, i.e. given ID and year, returns all records older than given year.
A request is to make it thread safe. Could any one give me some suggestion about how to make the dictionary thread safe, assuming there will be lots of threads calling record and find_history at the same time?
class Records:
def __init__(self):
self.map = {} # ID -> [year, location]
def record(self, ID, year, location):
if ID not in self.map:
self.map[ID] = []
self.map[ID].append([year, location])
def find_history(self, ID, year):
if ID not in self.map:
return []
results = []
for record in self.map[ID]:
if record[0] <= year:
results.append(record)
return results
Thanks a lot!
I tried reading python multithreading, still no clue.
Jone Shi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.