假设我有一个用python编写的网络机器人,通过POST请求向网站发送数据。数据逐行从文本文件中提取并传递到数组中。目前,我正在通过一个简单的for循环测试数组中的每个元素。我如何才能有效地实现多线程来更快地遍历数据。假设文本文件相当大。为每个请求附加一个线程是明智的吗?你认为最好的方法是什么?
with open("c:file.txt") as file:
dataArr = file.read().splitlines()
dataLen = len(open("c:file.txt").readlines())-1
def test(data):
#This next part is pseudo code
result = testData('www.example.com', data)
if result == 'whatever':
print 'success'
for i in range(0, dataLen):
test(dataArr[i])
我在想一些沿着这条线,但我觉得它会导致问题取决于文本文件的大小。我知道有一些软件允许终端用户在处理大量数据时指定线程的数量。我不完全确定这是如何工作的,但这是我想实现的。
import threading
with open("c:file.txt") as file:
dataArr = file.read().splitlines()
dataLen = len(open("c:file.txt").readlines())-1
def test(data):
#This next part is pseudo code
result = testData('www.example.com', data)
if result == 'whatever':
print 'success'
jobs = []
for x in range(0, dataLen):
thread = threading.Thread(target=test, args=(dataArr[x]))
jobs.append(thread)
for j in jobs:
j.start()
for j in jobs:
j.join()
这听起来像是multiprocessing.Pool
的配方
请看这里:https://docs.python.org/2/library/multiprocessing.html#introduction
from multiprocessing import Pool
def test(num):
if num%2 == 0:
return True
else:
return False
if __name__ == "__main__":
list_of_datas_to_test = [0, 1, 2, 3, 4, 5, 6, 7, 8]
p = Pool(4) # create 4 processes to do our work
print(p.map(test, list_of_datas_to_test)) # distribute our work
输出如下:
[True, False, True, False, True, False, True, False, True, False]
由于全局解释器锁,线程在python中很慢。你应该考虑在Python multiprocessing
模块中使用多个进程,而不是线程。使用多个进程可以增加代码的"上升"时间,因为生成一个真正的进程比一个轻线程需要更多的时间,但是由于GIL, threading
不会做你想要的。
这里和这里是关于使用multiprocessing
模块的一些基本资源。下面是第二个链接中的一个例子:
import multiprocessing as mp
import random
import string
# Define an output queue
output = mp.Queue()
# define a example function
def rand_string(length, output):
""" Generates a random string of numbers, lower- and uppercase chars. """
rand_str = ''.join(random.choice(
string.ascii_lowercase
+ string.ascii_uppercase
+ string.digits)
for i in range(length))
output.put(rand_str)
# Setup a list of processes that we want to run
processes = [mp.Process(target=rand_string, args=(5, output)) for x in range(4)]
# Run processes
for p in processes:
p.start()
# Exit the completed processes
for p in processes:
p.join()
# Get process results from the output queue
results = [output.get() for p in processes]
print(results)