python线程安全对象缓存 [英] python threadsafe object cache

查看:326
本文介绍了python线程安全对象缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了python网络服务器.每个http请求都会产生一个新线程. 我需要在内存中缓存对象,并且由于它是Web服务器,因此我希望缓存是线程安全的. python中是否有线程安全对象缓存的标准实现?我发现了以下

I have implemented a python webserver. Each http request spawns a new thread. I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following

http://freshmeat.net/projects/lrucache/

这看起来不是线程安全的.有人可以指出我在python中良好的线程安全缓存实现吗?

This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python?

谢谢!

推荐答案

默认情况下,Python中的许多操作都是线程安全的,因此标准字典应该没问题(至少在某些方面而言).这主要是由于GIL,这将有助于避免一些更严重的线程问题.

Well a lot of operations in Python are thread-safe by default, so a standard dictionary should be ok (at least in certain respects). This is mostly due to the GIL, which will help avoid some of the more serious threading issues.

这里有一个列表: http://coreygoldberg.blogspot .com/2008/09/python-thread-synchronization-and.html 可能有用.

There's a list here: http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronization-and.html that might be useful.

尽管这些操作的原子性质仅意味着如果您有两个线程同时访问字典,则不会有完全不一致的状态.这样您就不会有损坏的值.但是,您(像大多数多线程编程一样)将无法依赖那些原子操作的特定顺序.

Though atomic nature of those operation just means that you won't have an entirely inconsistent state if you have two threads accessing a dictionary at the same time. So you wouldn't have a corrupted value. However you would (as with most multi-threading programming) not be able to rely on the specific order of those atomic operations.

因此,简而言之...

So to cut a long story short...

如果您有非常简单的要求,而不必担心写入高速缓存的顺序,那么您可以使用字典并知道您将始终获得一致/未损坏的值(它可能会会过时).

If you have fairly simple requirements and aren't to bothered about the ordering of what get written into the cache then you can use a dictionary and know that you'll always get a consistent/not-corrupted value (it just might be out of date).

如果要确保读写方面的一致性,那么您可能需要查看Django的本地内存缓存:

If you want to ensure that things are a bit more consistent with regard to reading and writing then you might want to look at Django's local memory cache:

http://code.djangoproject. com/browser/django/trunk/django/core/cache/backends/locmem.py

使用读/写锁进行锁定.

Which uses a read/write lock for locking.

这篇关于python线程安全对象缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆