python多线程资源共享_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个位置相关。我没有使用口述,因为名单是有序的。在

我所做的是:

^{pr2}$

所以,用这个例子,我想可以把一个函数变成这样:#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值