我是多线程处理的新手,所以如果我扼杀条款或遗漏一些明显的东西,请原谅我。
与依次调用相同两个函数的不同代码相比,下面的代码没有任何时间优势。
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,四核处理器。任何帮助,将不胜感激。