python - How to lock and modify a dictionary safety per unit 'group' -
the following code not real code. made simple asking question.
server side code of web application.
what want locking group when modified don't know how.
example, user belongs 'groupa' posted request server, , want add user_id dictionary of 'groupa' safety.
want lock dictionary 'groupa' contains. don't want lock dictionary 'groups' contains.
because users belongs 'groupb' never modify dictionary 'groupa' contains
please give me advise.
# dictionary mutable means new groups added anytime groups = {'groupa': {}, 'groupb': {}, 'groupc': {}} def request_handler(request): # assuming these come user's http post user_id = request.userid user_group = request.user_group group = groups[user_group] # group contains user_id's dictionary if user_id in group: # value of key 'user_id' number of user's post group[user_id] = group[user_id] + 1 else: group.append(user_id) group[user_id] = 1
you need separate lock each group. e.g.:
groups = {'groupa': (threading.lock(), {}), 'groupb': (threading.lock(), {})} def request_handler(request): # assuming these come user's http post user_id = request.userid user_group = request.user_group glock, group = groups[user_group] glock: group[user_id] = group.get(user_id, 0) + 1
if groups dynamic, need lock groups
must acquired before groups added or removed.
consider other approaches:
- use own mapping classes groups subclass dict , use locks appropriately.
- have single thread responsible reading , updating groups. have other threads send tasks through pair of
queue
s. (now don't need locking @ all.)
Comments
Post a Comment