多线程python抓取所需的锁?
问题描述:
我有一个邮编列表,我想要使用yelp fusion api来提取商家信息。每个邮政编码必须至少进行一次api调用(通常更多),因此,我希望能够跟踪我的api使用情况,因为每日限制为25000.我已将每个邮政编码定义为用户定义的区域设置的实例类。这个语言环境类有一个类变量Locale.pulls,它充当拉动次数的全局计数器。多线程python抓取所需的锁?
我想多线程使用多处理模块,但我不知道是否需要使用锁,如果是的话,我该怎么做?关注点是竞态条件,因为我需要确保每个线程都能看到当前的pulls数量,这个数量在下面的伪代码中定义为Zip.pulls类变量。
import multiprocessing.dummy as mt
class Locale():
pulls = 0
MAX_PULLS = 20000
def __init__(self,x,y):
#initialize the instance with arguments needed to complete the API call
def pull(self):
if Locale.pulls > MAX_PULLS:
return none
else:
# make the request, store the returned data and increment the counter
self.data = self.call_yelp()
Locale.pulls += 1
def main():
#zipcodes below is a list of arguments needed to initialize each zipcode as a Locale class object
pool = mt.Pool(len(zipcodes)/100) # let each thread work on 100 zipcodes
data = pool.map(Locale, zipcodes)
答
一个简单的解决方案是在运行map()
之前检查len(zipcodes) < MAP_PULLS
。