【发布时间】:2013-12-26 10:36:18
【问题描述】:
我想使用concurrent.futures 模块为我的程序启用并行处理/线程。
不幸的是,我似乎找不到任何使用 concurrent.futures 模块的好、简单、防白痴的例子。他们通常需要更高级的 Python 知识或处理/线程概念和行话。
下面是一个基于我的程序的简化的、独立的示例:有一个纯 CPU 绑定任务非常适合多处理,还有一个单独的 IO 绑定任务插入到数据库 (SQLite)。 在我的程序中,我已经将其转换为使用多处理池类,但是由于 CPU 绑定任务的结果都被收集起来等待任务完成,它使用了大量的内存。 因此,我希望使用线程/处理的组合,我相信 concurrent.futures 可以相当简单地为我做。
那么如何将下面的内容转换成使用这个模块的东西呢?
import sqlite3
#Stand in CPU intensive task
def calculate(value):
return value * 10
#Stand in Thread I/O intensive task
def output(value):
global db
if (value % 1000) == 0:
db.execute('delete from test_table')
db.execute('insert into test_table (result) values (?)', (value,))
def main():
global db
results = []
db = sqlite3.connect('e:\\z_dev\\test.sqlite')
db.cursor()
#=========
#Perform CPU intensive task
for i in range(1000):
results.append( calculate(i))
#Perform Threading intensive task
for a in results:
output(a)
#=========
db.commit()
db.close()
if __name__ == '__main__':
main()
我正在寻找一个不使用任何花哨/复杂的 python 的答案。或者一个很好的清晰简单的解释,或者两者兼而有之!
谢谢
编辑:我当前的“多处理器”实现。可能是错误的,但它似乎有效。没有任何线程。这进入了上面的“#=========”部分。
#Multiprocessing
pool = multiprocessing.Pool(None)
for i in range(1000):
results.append( pool.apply_async(calculate(i)))
pool.close()
pool.join()
for i in results:
results[i] = results[i].get()
#Complete lack of threading; but if I had it, it'd be here:
for a in results:
output(a)
【问题讨论】:
标签: python multithreading python-3.x