【发布时间】:2017-07-06 13:51:16
【问题描述】:
我有一个函数可以懒惰地从一个巨大的 CSV 文件中生成行:
def get_next_line():
with open(sample_csv,'r') as f:
for line in f:
yield line
def do_long_operation(row):
print('Do some operation that takes a long time')
我需要使用线程,这样我从上述函数中获得的每条记录都可以调用do_long_operation。
互联网上的大多数地方都有这样的例子,我不太确定我是否走在正确的道路上。
import threading
thread_list = []
for i in range(8):
t = threading.Thread(target=do_long_operation, args=(get_next_row from get_next_line))
thread_list.append(t)
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()
我的问题是:
如何只启动有限数量的线程,比如 8 个?
如何确保每个线程都能从
get_next_line获得一行?
【问题讨论】: