的問題在這裏是最簡單的多線程的例子,我發現迄今:的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