2011-09-19 34 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