雑学1473612 views
中学英語811710 views
高校倫理1440106 views
中学理科1630641 views
ヒストリア290598 views
世界の国564520 views
Computer368106 views
数学講師2886227 views
高校日本史190571 views
LaTeX962153 views
Help
Tools
NewsSpreadsheetCalendarSlidesTier ListPen ToolIllustrationCrayonPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsCross SectionsMotion PathMechanicsWavesLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic Theory

English

Python のスレッドを開始・終了する

スレッドを作成したら、start() で開始し、join() で終了を待ちます。また、デーモンスレッドを使えば、メインプログラムの終了時に自動的にスレッドを終了させることもできます。

start() でスレッドを開始する

start() メソッドを呼ぶと、スレッドが実行を開始します。

import threading
import time

def task():
    print("タスク開始")
    time.sleep(2)
    print("タスク終了")

thread = threading.Thread(target=task)
print("start() 前")
thread.start()  # ここでスレッドが開始
print("start() 後")  # すぐに実行される(待たない)

start() は非ブロッキングで、すぐに次の行に進みます。

join() でスレッドの終了を待つ

join() を呼ぶと、そのスレッドが終了するまでブロックします。

import threading
import time

def task():
    print("タスク開始")
    time.sleep(2)
    print("タスク終了")

thread = threading.Thread(target=task)
thread.start()
print("join() 前")
thread.join()  # スレッドが終了するまで待機
print("join() 後")  # スレッド終了後に実行される

join() のタイムアウト

join() にタイムアウトを指定できます。

import threading
import time

def long_task():
    time.sleep(10)

thread = threading.Thread(target=long_task)
thread.start()

thread.join(timeout=2)  # 最大2秒待つ

if thread.is_alive():
    print("スレッドはまだ実行中")
else:
    print("スレッドは終了した")

タイムアウトしても、スレッド自体は終了しません。単に待機を中断するだけです。

is_alive() で状態を確認する

スレッドが実行中かどうかを確認できます。

import threading
import time

def task():
    time.sleep(1)

thread = threading.Thread(target=task)

print(f"開始前: {thread.is_alive()}")  # False
thread.start()
print(f"実行中: {thread.is_alive()}")  # True
thread.join()
print(f"終了後: {thread.is_alive()}")  # False

デーモンスレッド

デーモンスレッドは、メインプログラムが終了すると自動的に終了するスレッドです。

import threading
import time

def background_task():
    while True:
        print("バックグラウンド処理中...")
        time.sleep(1)

# daemon=True でデーモンスレッドに
thread = threading.Thread(target=background_task, daemon=True)
thread.start()

time.sleep(3)
print("メイン終了")
# メイン終了と同時にデーモンスレッドも終了
通常のスレッド

メインが終了しても、スレッドが終わるまでプログラムは終了しない。

デーモンスレッド

メインが終了すると、強制的に終了される。クリーンアップは行われない。

デーモンスレッドの注意点

デーモンスレッドは強制終了されるため、ファイル書き込みなど完了を保証したい処理には向きません。

import threading
import time

def write_file():
    with open("output.txt", "w") as f:
        for i in range(10):
            f.write(f"Line {i}\n")
            time.sleep(0.5)
    print("書き込み完了")  # 実行されない可能性あり

# デーモンスレッドだと途中で終了する危険
thread = threading.Thread(target=write_file, daemon=True)
thread.start()
time.sleep(1)
print("メイン終了")

複数スレッドの開始と終了

複数スレッドを効率的に管理するパターンです。

import threading
import time

def worker(n):
    time.sleep(n * 0.5)
    print(f"Worker {n} 完了")

# スレッドを作成して開始
threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

# すべてのスレッドの終了を待つ
for t in threads:
    t.join()

print("すべて完了")

start()join() を適切に使い分けることで、スレッドのライフサイクルを制御できます。