以下是我目前发现的最简单的多线程示例:import multiprocessing
import subprocess
def calculate(value):
return value * 10
if __name__ == '__main__':
pool = multiprocessing.Pool(None)
tasks = range(10000)
results = []
r = pool.map_async(calculate, tasks, callback=results.append)
r.wait() # Wait on the results
print results
我有两个列表和一个索引来访问每个列表中的元素。第一个列表中的第i个位置与第二个列表中的第i个位置相关。我没有使用口述,因为名单是有序的。在
我所做的是:
^{pr2}$
所以,用这个例子,我想可以把一个函数变成这样:#global variables first_list, second_list, i
first_list, second_list, i = None, None, 0
#initialize the lists
...
#have a function to do what the loop did and inside it increment i
def function:
#do stuff
i += 1
但是,这使得i成为共享资源,我不确定这是否安全。在我看来,我的设计并没有很好地支持这种多线程方法,但我不确定如何修复它。在
下面是一个我想要的工作示例(编辑您想要使用的图像):import multiprocessing
import subprocess, shlex
links = ['http://www.example.com/image.jpg']*10 # don't use this URL
names = [str(i) + '.jpg' for i in range(10)]
def download(i):
command = 'wget -O ' + names[i] + ' ' + links[i]
print command
args = shlex.split(command)
return subprocess.call(args, shell=False)
if __name__ == '__main__':
pool = multiprocessing.Pool(None)
tasks = range(10)
r = pool.map_async(download, tasks)
r.wait() # Wait on the results