Python线程无法同时运行
问题内容:
我是多线程处理的新手,所以如果我屠杀条款或错过明显的内容,请原谅我。
与不同的代码一个接一个地调用相同的两个函数相比,下面的代码没有任何时间优势。
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。任何帮助,将不胜感激。
问题答案:
您可以查看有关GIL的良好答案。
简而言之,如果您的任务受CPU限制(就像您发布的任务一样),线程将无法为您提供帮助。Python线程非常适合IO绑定任务,例如检索网页。