2011-09-19 38 views
1

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

你不需要'shlex.split()'只需要做:'args = ['wget','-O',names [i],links [i]]''。 – jfs

回答

1

首先,它可能是有益的,使元組的一個列表,例如

new_list[i] = (first_list[i], second_list[i]) 

這樣,當你改變i,可以確保你總是在同一個項目從first_listsecond_list操作。其次,假設列表中的ii-1條目之間沒有關係,您可以使用您的函數對給定的i值進行操作,並生成一個線程來處理每個i值。考慮

indices = range(len(new_list)) 
results = [] 
r = pool.map_async(your_function, indices, callback=results.append) 
r.wait() # Wait on the results 

這應該給你你想要的。

+0

我嘗試過,但似乎是另一個複雜因素阻止它的工作。在函數內部我稱之爲'subprocess.call',但隨後每個線程結束等待它完成,這意味着多進程的做法是行不通的。如果我使用subprocess.Popen,它會產生太多的進程。有沒有辦法解決這個問題? – multi

+0

'subprocess.call'和'subprocess.Popen'應該具有相同的功能。你能用確切的代碼編輯你的問題嗎? – brc

+0

'的過程subprocess.call'等待完成和'subprocess.popen'只是派生多個進程。至少這是'wget'的經驗。 http://docs.python.org/library/subprocess.html我猜他們是相同的,如果你做了'Popen'和'等待()'雖然。 – multi