Skip to content

Commit 0266737

Browse files
authored
Move code and advice about condition.wait() until there are two threads (#1440)
1 parent f7bc95e commit 0266737

1 file changed

Lines changed: 10 additions & 11 deletions

File tree

book/scheduling.md

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -303,24 +303,13 @@ class TaskRunner:
303303
task.run()
304304
305305
self.condition.acquire(blocking=True)
306-
if len(self.tasks) == 0:
307-
self.condition.wait()
308306
self.condition.release()
309307
```
310308

311-
It's important to call `wait` at the end of the `run` loop if there is nothing
312-
left to do. Otherwise that thread will tend to use up a lot of the CPU,
313-
plus constantly be acquiring and releasing `condition`. This busywork not only
314-
slows down the computer, but also causes the callbacks from the `Timer` to
315-
happen at erratic times, because the two threads are competing for the
316-
lock.[^try-it]
317-
318309
[condition-variable]: https://docs.python.org/3/library/threading.html#threading.Condition
319310

320311
[lock-class]: https://docs.python.org/3/library/threading.html#threading.Lock
321312

322-
[^try-it]: Try removing this code and observe. The timers will become quite
323-
erratic.
324313

325314
When using locks, it's super important to remember to release the lock
326315
eventually and to hold it for the shortest time possible. The code
@@ -1352,6 +1341,16 @@ class TaskRunner:
13521341
self.condition.release()
13531342
```
13541343

1344+
It's important to call `condition.wait` at the end of the `run` loop if
1345+
there is nothing left to do. Otherwise that thread will tend to use up a lot of
1346+
the CPU, plus constantly be acquiring and releasing `condition`. This busywork
1347+
not only slows down the computer, but also causes the callbacks from the
1348+
`Timer` to happen at erratic times, because the two threads are competing for
1349+
the lock.[^try-it]
1350+
1351+
[^try-it]: Try removing this code and observe. The timers will become quite
1352+
erratic.
1353+
13551354
The `Browser` should no longer call any methods on the `Tab`. Instead,
13561355
to handle events, it should schedule tasks on the main thread. For
13571356
example, here is loading:

0 commit comments

Comments
 (0)