-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrooms.py
48 lines (41 loc) · 1.33 KB
/
rooms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import uuid
from room import *
# 单例装饰器
def singleton(cls, *args, **kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
@singleton
class Rooms (object):
def __init__(self):
self.namespace = uuid.uuid1()
self.rooms = {}
def get_next_gid(self):
'''
获取一个不重复的gid
具体实现是:使用 Rooms 实例建立时的 uuid1 做 namespace, len(rooms) 做 name, 生成出来的 uuid3
'''
gid = uuid.uuid3(self.namespace, str(len(self.rooms)))
return str(gid)
def new_room(self):
gid = self.get_next_gid()
self.rooms[gid] = Room(gid)
return gid
def clean(self):
'''
清除空的房间,避免无效的内存占用
'''
cnt = 0
for i in list(self.rooms): # use list to force a copy of the keys to be made, https://stackoverflow.com/questions/11941817/how-to-avoid-runtimeerror-dictionary-changed-size-during-iteration-error
if len(self.rooms[i].get_members()) <= 0:
self.rooms.pop(i)
cnt += 1
return cnt
def get_count_rooms(self):
"""
获取当前房间总数
"""
return len(self.rooms)