Condition variable examples can be improved to show cv's main purpose - handling variables under a lock
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
I think this section Condition Objects can be improved to show in examples how shared state can be handled with condition objects:
https://docs.python.org/3/library/threading.html#condition-objects
This section does mention that condition variables are supposed to be evaluated/modified under a lock, but does not give any examples on how they are supposed to be handled.
Also, worth noting that the term condition variable in original contexts, such as C++ std::condition_variable or POSIX' pthread_cond_wait, refers to the machinery that provides atomic access to some shared state, not like Python does, calling shared state as condition variables protected by condition objects.
One would typically use a condition variable for things like waiting on non-waitable conditions, like a plain in-memory queue or an app stop request. So, a condition variable could be used in order to guarantee atomic handling of both conditions like this (ignoring exceptions):
cv.acquire()
while not stop_app:
if myq.is_empty():
cv.wait() # unlocks; allows other threads queue work and stop app
# locks again
continue # re-evaluate both conditions under the lock
req = myq.get() # myq has no locking on its own
cv.release()
process(req) # expensive - must be outside the lock
cv.acquire()
cv.release()
The queue and the application stop request represent the shared state protected by the condition variable. Something along these lines would be helpful on this page, perhaps with a better structured with block.
Also, current examples, like this one:
with cv:
while not an_item_is_available():
cv.wait()
get_an_available_item()
, do not highlight that an_item_is_available may only be an in-memory operation and if something expensive is done there, it will block the app from being able to queue new work or stop.
The example should show how the work item is retrieved and how it is processed. An assignment should be made where get_an_available_item is called and same emphasis can be provided that it must be an in-memory operation that cannot block at all, not even with a timeout.
The work item that was obtained above should be passed into some kind of a processing function outside of the with cv: block, so items are processed outside of the lock.
This is just a suggestion. If you feel current description is good enough for the intended audience, go ahead and close this issue.
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 Python threading 文件的 Condition Objects 區段開始,並將現有範例與回報的共用狀態使用案例進行比較。修改範例,使其展示受保護的記憶體內狀態、在條件鎖定下進行擷取,以及在鎖定外進行處理;完成的標準是文件清楚說明鎖定邊界和重新評估行為。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 48/100