猫型エンジニアのブログ

プログラム/ネットワーク系の技術関連をまとめたページです 

Pythonでマルチスレッド

 Pythonでマルチスレッドのプログラムを書いてみました。

マルチスレッドの基本

 5つのスレッドを起動して、Hello,worldと各スレッドの名前を出力するプログラムです。

import threading

def Hello():
    print "Hello,world"
    return

threads = []
for num in range(5):
    thread = threading.Thread(target=Hello())
    threads.append(thread)
    thread.start()
    print thread.getName()

実行結果

# python thread.py
Hello,world
Thread-1
Hello,world
Thread-2
Hello,world
Thread-3
Hello,world
Thread-4
Hello,world
Thread-5