的问题在这里是最简单的多线程的例子,我发现迄今:的Python:大约多/多线程和共享资源
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个位置相关。我没有使用字典,因为列表是有序的。
我在做什么是一样的东西:
for i in xrange(len(first_list)):
# do something with first_list[i] and second_list[i]
因此,使用这个例子,我觉得可以做一个函数排序是这样的:
#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
你不需要'shlex.split()'只需要做:'args = ['wget','-O',names [i],links [i]]''。 – jfs