我的代码不是真正的代码。我把这个问题简单化了。
这是web应用程序的服务器端代码。
我想做的是在组被修改时锁定它,但我不知道怎么做。
例如,属于“GroupA”的用户向服务器发布了一个请求,我想将该用户的标识添加到“GroupA”安全字典中。
我只想锁定'GroupA'包含的字典。我不想锁定“组”包含的词典。
因为属于“GroupB”的用户从不修改“GroupA”包含的词典
请给我建议。在
# this dictionary is mutable which means new groups could be added anytime
groups = {'GroupA': {}, 'GroupB': {}, 'GroupC': {}}
def request_handler(request):
# Assuming these come from the user's http post
user_id = request.userid
user_group = request.user_group
group = groups[user_group] # a group contains user_id's dictionary
if user_id in group:
# the value of the key 'user_id' is the number of the user's post
group[user_id] = group[user_id] + 1
else:
group.append(user_id)
group[user_id] = 1
每个组都需要一个单独的锁。E、 g.:
如果组也是动态的,则还需要
groups
的锁,必须在添加或删除任何组之前获取该锁。在考虑其他方法:
相关问题 更多 >
编程相关推荐