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"
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?
Using Python 2.7.5 on Windows 8.1, quad-core processor. Any help would be appreciated.
There are good answers regarding the GIL you can look at.
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.
链接地址: http://www.djcxy.com/p/55216.html上一篇: Python多线程最佳实践
下一篇: Python线程不会同时运行