Python线程不会同时运行

Jim*_*m V 5 python multithreading

我是多线程处理的新手,所以如果我屠宰条款或遗漏一些明显的东西,请原谅我.

下面的代码不会提供任何时间优势,而不是相继调用相同的两个函数的不同代码.


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"
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能使线程同时进行?GIL是否意味着并发只能通过单独的流程来实现?如果是这样,那么多线程的重点是什么?

在Windows 8.1上使用Python 2.7.5,四核处理器.任何帮助,将不胜感激.

Rol*_*Max 8

关于你可以看到的GIL有很好的答案.

简而言之,如果您的任务受CPU限制(就像您发布的那些),线程将无法帮助您.Python线程适用于IO绑定任务,例如检索网页.