Python threading ライブラリ完全ガイド
Python 標準ライブラリの threading は、マルチスレッドプログラミングをサポートするためのツールを提供します。本記事では、threading の主要な機能とその活用方法について詳しく解説します。
1. threading ライブラリの概要
threadingは、Python でマルチスレッドを利用するための標準ライブラリです。- スレッドを使用することで、並行処理が可能になります。
GIL (Global Interpreter Lock)の影響で CPU バウンドタスクでは効果が限定的ですが、I/O バウンドタスクには有効です。
インストール方法
threading は Python の標準ライブラリなので、追加のインストールは不要です。
import threading
import threading
import time
def worker():
print("スレッド開始")
time.sleep(2)
print("スレッド終了")
thread = threading.Thread(target=worker)
thread.start()
thread.join() # メインスレッドでスレッドの完了を待つ
import threading
lock = threading.Lock()
count = 0
def increment():
global count
with lock:
for _ in range(100000):
count += 1
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print("最終カウント:", count)
import threading
import time
event = threading.Event()
def worker():
print("待機中...")
event.wait()
print("処理開始!")
thread = threading.Thread(target=worker)
thread.start()
time.sleep(2)
event.set() # スレッドを解放
import threading
def delayed_task():
print("3秒後に実行されました!")
threading.Timer(3, delayed_task).start()
from concurrent.futures import ThreadPoolExecutor
import time
def worker(n):
time.sleep(1)
return f"完了: {n}"
with ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(worker, range(5))
for result in results:
print(result)
import threading
import time
def daemon_task():
while True:
print("デーモンスレッド動作中...")
time.sleep(1)
daemon_thread = threading.Thread(target=daemon_task, daemon=True)
daemon_thread.start()
time.sleep(3) # メインスレッドが終了すると、デーモンスレッドも終了
import threading
condition = threading.Condition()
shared_data = []
def producer():
with condition:
shared_data.append("データ")
print("データを追加しました")
condition.notify()
def consumer():
with condition:
condition.wait()
print("データを取得しました:", shared_data.pop())
threading.Thread(target=consumer).start()
threading.Thread(target=producer).start()
import threading
import time
semaphore = threading.Semaphore(2)
def worker(n):
with semaphore:
print(f"スレッド {n} 開始")
time.sleep(2)
print(f"スレッド {n} 終了")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
import threading
import time
barrier = threading.Barrier(3)
def worker(n):
print(f"スレッド {n} 待機中...")
barrier.wait()
print(f"スレッド {n} 実行開始")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
import threading
def worker():
print("スレッド ID:", threading.get_ident())
print("スレッド名:", threading.current_thread().name)
thread = threading.Thread(target=worker, name="MyThread")
thread.start()
thread.join()