Please read the README
Project description
ThreadSafeVariable
The problem
Imagine you have class like this
class A(object):
def __init__(self, x):
self.x = x
a = A(3)
print(a.x)
a.x
is a member variable of object a
. It is not thread safe. This means that if one thread changes `a.x``, all other threads see the new value. You can avoid this using a thread local object:
import threading
class A(object):
def __init__(self, x):
self.local = threading.local()
self.local.x
a = A(3)
print(a.local.x)
This works but has two downsides:
- you have changed the syntax
- even if a is accessible from other threads, a.local.x is only defined for the one thread that created the object
The ThreadSafeVariable module helps solve this problem and preserves the original syntax.
The solution
We change the code in the first example by declaring which variables should the thrad safe:
from threadsafevariable import ThreadSafeVariable
class A(object):
x = ThreadSafeVariable() # we add this line
def __init__(self, x):
self.x = x
a = A(3)
print(a.x)
We have preserved the syntax for the first example but a.x is now a thread local variable.
In addition we can do:
iceblock = ThreadSafeVariable.freeze()
This will store a snapshot all ThreadSafeVariable(s) of all objects defined in the current thread. Then for any other thread:
ThreadSafeVariable.restore(iceblock)
will restore all variables of all objects in this thread to the value stores in iceblock.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for threadsafevariable-20230507.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0849b5535fd2cc11fb659e7ff7cd3a6e617cffea4891c262a0a1b068c2664551 |
|
MD5 | 98b51a08bcf8518f1f00b8a31ca96af4 |
|
BLAKE2b-256 | 5b4db85162a28c4c6e3e0e4e4b5071b8110be3c4ef330a151e18622a9b13004a |
Hashes for threadsafevariable-20230507.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 45d86e8b8bb20f3d540457d5c0e814fe05aeda42758ee763bef476df28248d7e |
|
MD5 | 7799d3c22c2e9f15c0f6e7c44590ecd6 |
|
BLAKE2b-256 | 2070101c3bd85ad659aafdcf3ddf38096f4cd69bf478d57a8aae6787ac7d9b44 |