Python pymongo带有count()的空光标>;0
我试图创建一种队列,在这种队列中,许多进程都可以访问并原子化地处理一个项目:Python pymongo带有count()的空光标>;0,python,mongodb,pymongo,Python,Mongodb,Pymongo,我试图创建一种队列,在这种队列中,许多进程都可以访问并原子化地处理一个项目: while True: s= db.queue.find_and_modify({'service':'lock'},{'$set':{'locked':True}},upsert=True,new=False) # serves as a lock over the whole collection if s and s['locked']: # already locked by another pro
while True:
s= db.queue.find_and_modify({'service':'lock'},{'$set':{'locked':True}},upsert=True,new=False) # serves as a lock over the whole collection
if s and s['locked']: # already locked by another process
time.sleep(random.randint(2,10)) # sleep and try again
continue
else: # the lock was put by this process (atomic find_and_modify)
db.queue.update({'service':'lock'},{'$set':{'pid':process_id}}, upsert=True) # register the process who put the lock
res = db.queue.find({'when':{'$lte':last},'locked':False}).limit(1).sort('when',1) #select an available item
to_return = None #initialize with None
if res.count(): # 1 or more
to_return = res[0] #get the first item
to_return['locked'] = True # lock it
to_return['pid'] = process_id # register the process locking it
db.queue.save(to_return)
db.queue.update({'service':'lock'},{'$set':{'locked':False}}) # remove the global lock
return to_return
有时我会看到一个进程正在消失
在日志中我看到了一个例外:
Traceback (most recent call last):
File "driver.py", line 22, in getUserFromQueue
to_return = res[0]
IndexError("no such item for Cursor instance")
这意味着光标res
为空,
但是它怎么可能是空的,因为有一个全局锁:只有一个进程查询项目,并且它已经通过了条件if res.count()
,即光标中至少有一个项目
我必须创建全局锁的原因是我不能使用find_和modify的limit和sort