线程
单个线程
from time import time
def factorize(num):
for i in range(1, num+1):
if num % i == 0:
yield i
nums = [2139079, 1214759, 1516637, 1852285]
start = time()
for num in nums:
list(factorize(num))
end = time()
print(end-start)
# 0.4892253875732422
多个线程
from time import time
from threading import Thread
class FactorizeThread(Thread):
def __init__(self, num):
super().__init__()
self.num = num
def factorize(self, num):
for i in range(1, num+1):
if num % i == 0:
yield i
def run(self):
self.factors = list(self.factorize(self.num))
nums = [2139079, 1214759, 1516637, 1852285]
start = time()
threads = []
for num in nums:
thread = FactorizeThread(num)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
end = time()
print(end-start)
# 0.4903602600097656 因为GIl的原因无法真正并行计算
单线程处理阻塞式IO
from time import time
from select import select
def slow():
select([], [], [], 0.1)
start = time()
for _ in range(5):
slow()
end = time()
print(end-start)
# 0.5008544921875
多线程处理阻塞式IO
from time import time
from select import select
from threading import Thread
def slow():
select([], [], [], 0.1)
start = time()
threads = []
for _ in range(5):
thread = Thread(target=slow)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
end = time()
print(end-start)
# 0.10056090354919434 处理阻塞式IO速度快5倍
# Python 还有内置的 asyncio 模块来处理阻塞式IO
多线程之间数据竞争
from threading import Thread
num = 0
def buy():
global num
for i in range(1000000):
num += 1
threads = []
for _ in range(2):
thread = Thread(target=buy)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(num)
# 1351674 期望是 2000000
多线程用Lock避免数据竞争
from threading import Thread
from threading import Lock
num = 0
lock = Lock()
def buy():
global num
for i in range(1000000):
with lock:
num += 1
threads = []
for _ in range(2):
thread = Thread(target=buy)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(num)
# 2000000