threading

Python threading.local() 解說

我們都知道多個執行緒(thread)之間會共用 Process 的記憶體,那你覺得以下範例程式的執行結果會是什麼呢?這是 2 個執行緒分別做 +1 與 -1 運算各 100,000 次的 Python 程式:

import threading


def count(thread_name, step=1):
    global v
    for i in range(0, 100000):
        v += 1 * step
    print(f'{thread_name} -> ', v, flush=True)


v = 0
t1 = threading.Thread(target=count, args=('t1', 1, ))
t2 = threading.Thread(target=count, args=('t2', -1, ))
t1.start()
t2.start()
t1.join()
t2.join()

這段範例程式的執行結果,就跟本文要解說的 threading.local() 有關。

Posted on  Sep 4, 2023  in  Python 程式設計 - 高階  by  Amo Chen  ‐ 3 min read

Python daemon thread 解說

閱讀 Python Threading 文件時,關於 Thread Objects 中有提到 Daemon Thread

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.

單看說明其實還不是特別清楚,可以用個範例實際幫助理解。

Last updated on  Sep 8, 2023  in  Python 程式設計 - 中階  by  Amo Chen  ‐ 2 min read

Python threading event objects 溝通範例教學

The simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.

Threads(執行緒)之間溝通最簡單的方式,即是透過 Event Objects ,這種方式通常應用在 1 個 thread 發起 1 個 event ,然後其他 threads 會等待發出 event 的 thread ,譬如 1 個發號施令的 thread ,其他 threads 會等待該 thread 發號施令後才開始工作。

Last updated on  Jul 24, 2023  in  Python 程式設計 - 中階  by  Amo Chen  ‐ 2 min read