You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can also quickly try out this and other packages without having to install using [instld](https://github.com/pomponchik/instld).
49
+
You can also use [`instld`](https://github.com/pomponchik/instld) to quickly try out this package and others without installing them.
50
50
51
51
52
52
## Lock protocols
53
53
54
-
Protocols are needed so that you can write typed code without being bound to specific classes. Protocols from this library allow you to "equalize" locks from the standard library and third-party locks, including those provided by this library.
54
+
Protocols let you write type-annotated code without depending on concrete classes. The protocols in this library let you treat lock implementations from the standard library, third-party packages, and this library uniformly.
55
55
56
-
We consider the basic characteristic of the lock protocol to be the presence of two methods for an object:
56
+
At a minimum, a lock object should provide two methods:
57
57
58
58
```python
59
-
defacquire() -> None: pass
60
-
defrelease() -> None: pass
59
+
defacquire(self) -> None: ...
60
+
defrelease(self) -> None: ...
61
61
```
62
62
63
-
All the locks from the standard library correspond to this, as well as the locks presented in this one.
63
+
All standard library locks conform to this, as do the locks provided by this library.
64
64
65
-
To check for compliance with this minimum standard, `locklib` contains the `LockProtocol`. You can check for yourself that all the locks match it:
65
+
To check for compliance with this minimum standard, `locklib` contains the `LockProtocol`. You can verify that all of these locks satisfy it:
However! Most idiomatic python code using locks uses them as context managers. If your code is like that too, you can use one of the two inheritors of the regular`LockProtocol`: `ContextLockProtocol` or `AsyncContextLockProtocol`. Thus, the protocol inheritance hierarchy looks like this:
81
+
However, most idiomatic Python code uses locks as context managers. If your code does too, you can use one of the two protocols derived from the base`LockProtocol`: `ContextLockProtocol` or `AsyncContextLockProtocol`. Thus, the protocol hierarchy looks like this:
82
82
83
83
```
84
84
LockProtocol
85
85
├── ContextLockProtocol
86
86
└── AsyncContextLockProtocol
87
87
```
88
88
89
-
`ContextLockProtocol` describes the objects described by`LockProtocol`, which are also [context managers](https://docs.python.org/3/library/stdtypes.html#typecontextmanager). `AsyncContextLockProtocol`, by analogy, describes objects that are instances of `LockProtocol`, as well as[asynchronous context managers](https://docs.python.org/3/reference/datamodel.html#async-context-managers).
89
+
`ContextLockProtocol` describes objects that satisfy`LockProtocol` and also implement the [context manager protocol](https://docs.python.org/3/library/stdtypes.html#typecontextmanager). Similarly,`AsyncContextLockProtocol`describes objects that satisfy `LockProtocol` and implement the[asynchronous context manager](https://docs.python.org/3/reference/datamodel.html#async-context-managers) protocol.
90
90
91
-
Almost all the locks from the standard library are instances of `ContextLockProtocol`, as well as `SmartLock`.
91
+
Almost all standard library locks, as well as `SmartLock`, satisfy `ContextLockProtocol`:
However, the [`Lock` from asyncio](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Lock) belongs to a separate category and `AsyncContextLockProtocol` is needed to describe it:
105
+
However, the [`asyncio.Lock`](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Lock) belongs to a separate category and `AsyncContextLockProtocol` is needed to describe it:
106
106
107
107
```python
108
108
from asyncio import Lock
@@ -111,12 +111,12 @@ from locklib import AsyncContextLockProtocol
If you use type hints and static verification tools like [mypy](https://github.com/python/mypy), we highly recommend using the narrowest of the presented categories for lock protocols, which describe the requirements for your locales.
114
+
If you use type hints and static verification tools like [mypy](https://github.com/python/mypy), we highly recommend using the narrowest applicable protocol for your use case.
115
115
116
116
117
-
## `SmartLock`- deadlock is impossible with it
117
+
## `SmartLock`turns deadlocks into exceptions
118
118
119
-
`locklib`contains a lock that cannot get into the [deadlock](https://en.wikipedia.org/wiki/Deadlock)-`SmartLock`, based on [Wait-for Graph](https://en.wikipedia.org/wiki/Wait-for_graph). You can use it as a usual[```Lock``` from the standard library](https://docs.python.org/3/library/threading.html#lock-objects). Let's check that it can protect us from the [race condition](https://en.wikipedia.org/wiki/Race_condition) in the same way:
119
+
`locklib`includes a lock that prevents [deadlocks](https://en.wikipedia.org/wiki/Deadlock)—`SmartLock`, based on [Wait-for Graph](https://en.wikipedia.org/wiki/Wait-for_graph). You can use it like a regular[`Lock` from the standard library](https://docs.python.org/3/library/threading.html#lock-objects). Let’s verify that it prevents [race conditions](https://en.wikipedia.org/wiki/Race_condition) in the same way:
120
120
121
121
```python
122
122
from threading import Thread
@@ -126,11 +126,11 @@ lock = SmartLock()
126
126
counter =0
127
127
128
128
deffunction():
129
-
global counter
129
+
global counter
130
130
131
-
for _ inrange(1000):
132
-
with lock:
133
-
counter +=1
131
+
for _ inrange(1000):
132
+
with lock:
133
+
counter +=1
134
134
135
135
thread_1 = Thread(target=function)
136
136
thread_2 = Thread(target=function)
@@ -140,7 +140,7 @@ thread_2.start()
140
140
assert counter ==2000
141
141
```
142
142
143
-
Yeah, in this case the lock helps us not to get a race condition, as the standard ```Lock``` does. But! Let's trigger a deadlock and look what happens:
143
+
As expected, this lock prevents race conditions just like the standard `Lock`. Now let’s deliberately trigger a deadlock and see what happens:
144
144
145
145
```python
146
146
from threading import Thread
@@ -150,33 +150,33 @@ lock_1 = SmartLock()
150
150
lock_2 = SmartLock()
151
151
152
152
deffunction_1():
153
-
whileTrue:
154
-
with lock_1:
155
-
with lock_2:
156
-
pass
153
+
whileTrue:
154
+
with lock_1:
155
+
with lock_2:
156
+
pass
157
157
158
158
deffunction_2():
159
-
whileTrue:
160
-
with lock_2:
161
-
with lock_1:
162
-
pass
159
+
whileTrue:
160
+
with lock_2:
161
+
with lock_1:
162
+
pass
163
163
164
164
thread_1 = Thread(target=function_1)
165
165
thread_2 = Thread(target=function_2)
166
166
thread_1.start()
167
167
thread_2.start()
168
168
```
169
169
170
-
And... We have an exception like this:
170
+
This raises an exception like the following:
171
171
172
172
```
173
173
...
174
174
locklib.errors.DeadLockError: A cycle between 1970256th and 1970257th threads has been detected.
175
175
```
176
176
177
-
Deadlocks are impossible for this lock!
177
+
So, with this lock, a deadlock results in an exception instead of blocking forever.
178
178
179
-
If you want to catch the exception, import this from the `locklib` too:
179
+
If you want to catch this exception, you can also import it from `locklib`:
180
180
181
181
```python
182
182
from locklib import DeadLockError
@@ -185,9 +185,9 @@ from locklib import DeadLockError
185
185
186
186
## Test your locks
187
187
188
-
Sometimes, when testing a code, you may need to detect if some action is taking place inside the lock. How to do this with a minimum of code? There is the `LockTraceWrapper` for this. It is a wrapper around a regular lock, which records it every time the code takes a lock or releases it. At the same time, the functionality of the wrapped lock is fully preserved.
188
+
Sometimes, when testing code, you may need to detect whether some action occurs while the lock is held. How can you do this with minimal boilerplate? Use `LockTraceWrapper`. It is a wrapper around a regular lock that records every acquisition and release. At the same time, it fully preserves the wrapped lock’s behavior.
189
189
190
-
It's easy to create an object of such a lock. Just pass any other lock to the class constructor:
190
+
Creating such a wrapper is easy. Just pass any lock to the constructor:
191
191
192
192
```python
193
193
from threading import Lock
@@ -196,29 +196,29 @@ from locklib import LockTraceWrapper
196
196
lock = LockTraceWrapper(Lock())
197
197
```
198
198
199
-
You can use it in the same way as the wrapped lock:
199
+
You can use it exactly like the wrapped lock:
200
200
201
201
```python
202
202
with lock:
203
203
...
204
204
```
205
205
206
-
Anywhere in your program, you can "inform" the lock that the action you need is being performed here:
206
+
Anywhere in your program, you can record that a specific event occurred:
207
207
208
208
```python
209
209
lock.notify('event_name')
210
210
```
211
211
212
-
And! Now you can easily identify if there were cases when an event with this identifier did not occur under the mutex. To do this, use the `was_event_locked` method:
212
+
You can then easily check whether an event with this identifier ever occurred outside the lock. To do this, use the `was_event_locked` method:
213
213
214
214
```python
215
215
lock.was_event_locked('event_name')
216
216
```
217
217
218
-
If the `notify` method was called with the same parameter only when the lock activated, it will return `True`. If not, that is, if there was at least one case when the c method was called with such an identifier without an activated mutex, `False` will be returned.
218
+
If the `notify` method was called with the same parameter only while the lock was held, it will return `True`. If not, that is, if there was at least one case when the `notify` method was called with that identifier without the lock being held, `False` will be returned.
219
219
220
-
How does it work? A modified [algorithm for determining the correct parenthesis sequence](https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F_%D1%81%D0%BA%D0%BE%D0%B1%D0%BE%D1%87%D0%BD%D0%B0%D1%8F_%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C) is used here. For each thread for which any events were registered (taking the mutex, releasing the mutex, and also calling the `notify` method), the check takes place separately, that is, we determine that it was the same thread that held the mutex when `notify` was called, and not some other one.
220
+
How does it work? It uses a modified [balanced-parentheses algorithm](https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F_%D1%81%D0%BA%D0%BE%D0%B1%D0%BE%D1%87%D0%BD%D0%B0%D1%8F_%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C). For each thread for which any events were registered (taking the mutex, releasing the mutex, and also calling the `notify` method), the check takes place separately, that is, we determine that it was the same thread that held the mutex when `notify` was called, and not some other one.
221
221
222
-
> ⚠️ The thread id is used to identify the threads. This id may be reused if the current thread ends, which in some cases may lead to incorrect identification of lock coverage for operations that were not actually covered by the lock. Make sure that this cannot happen during your test.
222
+
> ⚠️ The thread id is used to identify the threads. A thread ID may be reused after a thread exits, which may in some cases cause the wrapper to incorrectly report that an operation was protected by the lock. Make sure this cannot happen during your tests.
223
223
224
-
If no event with the specified identifier was recorded in any of the threads, the `ThereWasNoSuchEventError` exception will be raised by default. If you want to disable this so that the method simply returns `False` in such situations, pass the additional argument `raise_exception=False` to `was_event_locked`.
224
+
If no event with the specified identifier was recorded in any thread, the `ThereWasNoSuchEventError` exception will be raised by default. If you want to disable this so that the method simply returns `False` in such situations, pass the keyword argument `raise_exception=False` to `was_event_locked`.
0 commit comments