python3.5线程:这个实现是否正确?

2024-04-27 02:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过在随机值列表中寻找素数来研究线程。我本以为使用线程可以加快速度,但线程化和非线程化的时间是一样的。这是因为我没有正确地实现吗?如何使用这样的示例演示线程的好处?你知道吗

import time
import threading
from math import sqrt
from random import randint

def findPrimes(aList):
    for testValue in aList:
        isPrime = True
        for i in range(2,int(sqrt(testValue)+1)):
            if testValue % i == 0:
                isPrime = False
        if isPrime:
            #print(testValue)
            pass

testValues1 = []
testValues2 = []
for i in range(1000):
    testValues1.append(randint(10,100))
    testValues2.append(randint(10,100))


t = time.process_time()
findPrimes(testValues1)
findPrimes(testValues2)
print('The long way',time.process_time() - t) # runs in 0.006 to 0.007


t = time.process_time()
thread1 = threading.Thread(target=findPrimes(testValues1))
thread2 = threading.Thread(target=findPrimes(testValues2))
thread1.start()
thread2.start()
print('The threading way',time.process_time() - t) # also runs in 0.006 to 0.007

Tags: infromimportfortime线程processprint
2条回答

Python中的线程只对IO绑定的操作有用,因为全局解释器锁(Global Interpreter Lock,GIL)本质上强制Python操作在lockstep中进行,而实际上从不并发进行。你知道吗

(但是,执行IO的线程(例如,与远程服务器通信或访问文件)可以而且通常比没有线程的速度更快。)

请参阅How to use threading in Python?以获取解决方案,例如改用multiprocessing模块。你知道吗

线程不能同时运行。。。线程的概念是,一个特定的线程能够与许多其他线程共享cpu时钟周期,这些线程可以模仿并发行为,但它们不能并行运行

相关问题 更多 >