【发布时间】:2016-02-23 19:51:54
【问题描述】:
我试图在处理器的多个线程上运行此 Python 代码,但我找不到如何分配多个线程。我在 Jupyter(以前的 IPython)中使用 python 2.7。
初始代码如下(所有这部分工作完美)。它是一个网络解析器,它接受x 即 my_list 中的一个 url 即一个 url 列表,然后编写一个 CSV(其中 out_string 是一行)。
没有多线程的代码
my_list = ['http://stackoverflow.com/', 'http://google.com']
def main():
with open('Extract.csv'), 'w') as out_file:
count_loop = 0
for x in my_list:
#================ Get title ==================#
out_string = ""
campaign = parseCampaign(x)
out_string += ';' + str(campaign.getTitle())
#================ Get Profile ==================#
if campaign.getTitle() != 'NA':
creator = parseCreator(campaign.getCreatorUrl())
out_string += ';' + str(creator.getCreatorProfileLinkUrl())
else:
pass
#================ Write ==================#
out_string += '\n'
out_file.write(out_string)
count_loop +=1
print '---- %s on %s ------- ' %(count_loop, len(my_list))
具有多线程但无法工作的代码
from threading import Thread
my_list = ['http://stackoverflow.com/', 'http://google.com']
def main(x):
with open('Extract.csv'), 'w') as out_file:
count_loop = 0
for x in my_list:
#================ Get title ==================#
out_string = ""
campaign = parseCampaign(x)
out_string += ';' + str(campaign.getTitle())
#================ Get Profile ==================#
if campaign.getTitle() != 'NA':
creator = parseCreator(campaign.getCreatorUrl())
out_string += ';' + str(creator.getCreatorProfileLinkUrl())
else:
pass
#================ Write ==================#
out_string += '\n'
out_file.write(out_string)
count_loop +=1
print '---- %s on %s ------- ' %(count_loop, len(my_list))
for x in my_list:
t = Thread(target=main, args=(x,))
t.start()
t2 = Thread(target=main, args=(x,))
t2.start()
我找不到实现多个线程来运行这段代码的好方法,而且我有点困惑,因为文档不是很容易理解。单核,这段代码需要2个小时,多线程会节省我很多时间!
【问题讨论】:
-
循环运行得更快,
-
这是我的代码的较短版本,实际版本每个循环需要 7 到 10 秒,因为有很多请求(外部 API),所以如果 10s * 12 000 urls 可以显着改善我的处理器的每个核心都被使用,即 core1 = 10s * 3000url s+ core2 = 10s * 3000urls + core3 = 10s * 3000urls + core4 = 10s * 3000urls 同时...
-
当你说多线程版本不工作时,你是什么意思。是否有错误,或者它只是没有运行得更快?检查这个问题,我不认为 ipython 使用多个内核,即使是线程模块。 stackoverflow.com/a/204150/5889975
-
python 没有针对多线程进行调整,原因有很多。试试
multiprocessing或asyncio。 -
请告诉我们“不工作”是什么意思。
标签: python multithreading python-2.7