私はマルチスレッド処理にまったく慣れていないので、用語を解体したり、明らかな何かを見落としたりした場合はご容赦ください。
以下のコードは、同じ 2 つの関数を次々に呼び出す別のコードよりも時間的に有利ではありません。
import time
import threading
start_time = time.clock()
def fibonacci(nth): #can be ignored
first = 0
second = 1
for i in range(nth):
third = first + second
first = second
second = third
print "Fibonacci number", i + 1, "is", len(str(first)), "digits long"
def collatz(collatz_max): #can be ignored
for n in range(collatz_max):
n = n + 1 #avoid entering 0
solution = []
solution.append(n)
while n != 1:
if n % 2 == 0:
n = n / 2
else:
n = (n*3) + 1
solution.append(n)
print "Path for Collatz number", collatz_max, "is", solution
def scripts():
thread_fibonacci = threading.Thread(target=fibonacci, args = (800000,))
thread_collatz = threading.Thread(target=collatz, args = (400000,))
thread_fibonacci.start()
thread_collatz.start()
return thread_fibonacci, thread_collatz
all_scripts = scripts()
#wait until both threads are finished
for script in all_scripts:
script.join()
print time.clock() - start_time, "seconds"
スレッドを同時に実行するにはどうすればよいですか? GIL とは、並行性は別々のプロセスによってのみ達成できるということですか? もしそうなら、マルチスレッドのポイントは何ですか?
Windows 8.1、クアッドコア プロセッサで Python 2.7.5 を使用。どんな助けでも大歓迎です。