Python线程无法同时运行 [英] Python threads don't run simultaneously
问题描述
我是多线程处理的新手,所以如果我屠杀条款或错过明显的内容,请原谅我.
I'm brand new to multi-threaded processing, so please forgive me if I butcher terms or miss something obvious.
下面的代码与调用一个相同的两个函数的不同代码没有任何时间优势.
The code below doesn't offer any time advantage over different code that calls the same two functions one after the other.
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意味着并发只能通过单独的过程来实现吗?如果是这样,多线程的意义何在?
What do I need to do to make the threads simultaneous? Does GIL mean concurrency can only be achieved through separate processes? If so, what is the point of multithreading?
在Windows 8.1(四核处理器)上使用Python 2.7.5.任何帮助将不胜感激.
Using Python 2.7.5 on Windows 8.1, quad-core processor. Any help would be appreciated.
推荐答案
关于您可以查看的GIL,有很好的答案.
There are good answers regarding the GIL you can look at.
简而言之,如果您的任务是CPU密集型的(就像您发布的任务一样),线程将无济于事. Python线程非常适合IO绑定任务,例如检索网页.
In short, if your tasks are CPU-bound (like the ones you posted), threads are not going to help you. Python threads are good for IO-bound tasks, like retrieving a web page.
这篇关于Python线程无法同时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!