まぐらぼ

日々の雑記を書いています。

グローバルインタプリタロック

Pythonインタプリタにはグローバルロック(GIL)があるのでCPU負荷は分散されません。ネットワークやI/O処理の非同期実行では効果があります。Stacklessというマルチスレッドに最適化したPythonの処理系があるそうですが使った事はありません。

djangoフレームワークは並列処理していないと思えないのでユーザ毎に個別プロセス生成しているのでしょうか。

例)

from threading import Thread
import cProfile

thread_list = []
thread = Thread(target=スレッド処理の関数, args=(引数))
thread_list.append(thread)
thread.daemon = True	# メインスレッド終了後の振る舞い
thread.start()


例2

def test_thread2():

    cpu_number = 4
    big_number = 100000
    thread_list = []
    for i in xrange(cpu_number):
        thread = Thread(target=spin_for_a_while, args=(big_number/cpu_number,))
        thread_list.append(thread)
        thread.daemon = True
        thread.start()

    for thread in thread_list:
        thread.join()

    return True

例3

def test_thread():
    th = TestThread()
    th.start()
     
    time.sleep(1)
    print "=== start main thread ==="
    for i in range(5):
        time.sleep(1)
        print "main thread : " + str(datetime.datetime.today())
    print "=== end main thread ==="