python多线程资源共享_Python:关于多处理/多线程和共享资源的问题
以下是我目前發(fā)現(xiàn)的最簡單的多線程示例: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個位置相關(guān)。我沒有使用口述,因?yàn)槊麊问怯行虻摹T?/p>
我所做的是:
^{pr2}$
所以,用這個例子,我想可以把一個函數(shù)變成這樣:#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成為共享資源,我不確定這是否安全。在我看來,我的設(shè)計(jì)并沒有很好地支持這種多線程方法,但我不確定如何修復(fù)它。在
下面是一個我想要的工作示例(編輯您想要使用的圖像):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
總結(jié)
以上是生活随笔為你收集整理的python多线程资源共享_Python:关于多处理/多线程和共享资源的问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hashmap value占用空间大小_
- 下一篇: 怎么让手机变成震动器_详解iPhone