在Python中存储快速更改数据的最佳方法是什么?

2024-07-05 11:03:47 发布

您现在位置:Python中文网/ 问答频道 /正文

为了学习一些关于Python和sockets的知识,我写了一个小的2d游戏服务器。在

尽管我在这个服务器上看到的人并不多,但我希望尽可能高效地编写它。在

我有一个名为“globuser”的全局字典,它是另一个包含用户统计信息的字典(比如X&Y坐标)

这是储存它们的最好方法吗?字典能有多大?
我想你也可以尝试使用一个常规的数据库,但这会非常慢。 或者我应该使用完全不同的方案?在

多个线程是否可以同时访问同一个变量,或者它们被挂起?
我想当很多用户在线时,每一个动作都需要更新。如果他们同时发生,太好了!但是如果他们都需要“锁定”变量,那就不那么好了。在


Tags: 方法用户服务器信息数据库游戏字典方案
2条回答

使用多处理而不是线程化。它有很多优点,其中一个优点是可以处理所有进程的全局存储。该模块使用由管理器初始化的全局字典。在

以下是取自PyMOTW的示例

The Manager is responsible for coordinating shared information state between all of its users. By creating the list through the manager, the list is updated in all processes when anyone modifies it. In addition to lists, dictionaries are also supported.

import multiprocessing

def worker(d, key, value):
    d[key] = value

if __name__ == '__main__':
    mgr = multiprocessing.Manager()
    d = mgr.dict()
    jobs = [ multiprocessing.Process(target=worker, args=(d, i, i*2))
             for i in range(10) 
             ]
    for j in jobs:
        j.start()
    for j in jobs:
        j.join()
    print 'Results:', d
$ python multiprocessing_manager_dict.py
Results: {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Namespaces

In addition to dictionaries and lists, a Manager can create a shared Namespace. Any named value added to the Namespace is visible across all of the clients.

import multiprocessing

def producer(ns, event):
    ns.value = 'This is the value'
    event.set()

def consumer(ns, event):
    try:
        value = ns.value
    except Exception, err:
        print 'Before event, consumer got:', str(err)
    event.wait()
    print 'After event, consumer got:', ns.value

if __name__ == '__main__':
    mgr = multiprocessing.Manager()
    namespace = mgr.Namespace()
    event = multiprocessing.Event()
    p = multiprocessing.Process(target=producer, args=(namespace, event))
    c = multiprocessing.Process(target=consumer, args=(namespace, event))

    c.start()
    p.start()

    c.join()
    p.join()
$ python multiprocessing_namespaces.py
Before event, consumer got: 'Namespace' object has no attribute 'value'
After event, consumer got: This is the value

我可能会考虑将用户存储为Player对象的列表。研究一下__slots__,因为这样可以在创建许多实例时节省内存。在

我也不会太担心现阶段的表现。首先编写代码,然后通过剖析器运行它,找出在优化名称中盲目更改是最慢的。在

关于线程安全和数据共享,我发现了this,它似乎提供了一些关于这个主题的信息。在

相关问题 更多 >