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:

  1. use own mapping classes groups subclass dict , use locks appropriately.
  2. have single thread responsible reading , updating groups. have other threads send tasks through pair of queues. (now don't need locking @ all.)

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -