Matthew Treinish | 0db5377 | 2013-07-26 10:39:35 -0400 | [diff] [blame] | 1 | # vim: tabstop=4 shiftwidth=4 softtabstop=4 |
| 2 | |
| 3 | # Copyright 2011 OpenStack Foundation. |
| 4 | # All Rights Reserved. |
| 5 | # |
| 6 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 7 | # not use this file except in compliance with the License. You may obtain |
| 8 | # a copy of the License at |
| 9 | # |
| 10 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | # |
| 12 | # Unless required by applicable law or agreed to in writing, software |
| 13 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 15 | # License for the specific language governing permissions and limitations |
| 16 | # under the License. |
| 17 | |
| 18 | """Greenthread local storage of variables using weak references""" |
| 19 | |
| 20 | import weakref |
| 21 | |
| 22 | from eventlet import corolocal |
| 23 | |
| 24 | |
| 25 | class WeakLocal(corolocal.local): |
| 26 | def __getattribute__(self, attr): |
| 27 | rval = corolocal.local.__getattribute__(self, attr) |
| 28 | if rval: |
| 29 | # NOTE(mikal): this bit is confusing. What is stored is a weak |
| 30 | # reference, not the value itself. We therefore need to lookup |
| 31 | # the weak reference and return the inner value here. |
| 32 | rval = rval() |
| 33 | return rval |
| 34 | |
| 35 | def __setattr__(self, attr, value): |
| 36 | value = weakref.ref(value) |
| 37 | return corolocal.local.__setattr__(self, attr, value) |
| 38 | |
| 39 | |
| 40 | # NOTE(mikal): the name "store" should be deprecated in the future |
| 41 | store = WeakLocal() |
| 42 | |
| 43 | # A "weak" store uses weak references and allows an object to fall out of scope |
| 44 | # when it falls out of scope in the code that uses the thread local storage. A |
| 45 | # "strong" store will hold a reference to the object so that it never falls out |
| 46 | # of scope. |
| 47 | weak_store = WeakLocal() |
| 48 | strong_store = corolocal.local |