2013-05-17 24 views
0

我試圖在mongodb中保存條目並獲取id。然後我想在線程中找到這個條目。但有時候我做不到。從pymongo的線程讀取沒有結果

import pymongo 
import bson 
import threading 

connection = pymongo.Connection("localhost", 27017) 
db = connection.test 

def set_cache(db): 
    cache_id = db.test_collection.save({'test': 'some string'}) 
    return cache_id 

def get_cache(db, cache_id): 
    entry = db.test_collection.find_one({'_id' : bson.objectid.ObjectId(cache_id)}) 
    if not entry: 
     print('No entry for %s' % cache_id) 

    return entry 

i = 0 
while 1: 
    i += 1 
    cache_id = set_cache(db) 

    t = threading.Thread(target=get_cache, args=(db, cache_id)) 
    t.start() 
    t.join() 

    if i > 10000: 
     break 

所以,有些事情我看到'沒有條目......'。但是我可以在mongo中看到這個條目。 python2.6 mongo 2.0.6

+0

我發現問題。使用保存選項w = 1 http://api.mongodb.org/python/current/api/pymongo/collection.html – user1794521

回答

2

實現的問題在於,您使用的默認用法爲pymongo.Connection的未確認寫入。通過使用這種方式,您可以進入寫入未在內存中確認但您在客戶端收到確認的情況。如果您更快地處理響應併發出查找請求,您將會遇到像這樣的情況。你基本上過快:)

現在,如果你使用應答write concern瓦特:1或使用新的pymongo.MongoClient類(我建議你這樣做),你就不會陷入這種局面只是用:

import pymongo 
import bson 
import threading 

connection = pymongo.MongoClient("localhost", 27017) 
db = connection.test 

def set_cache(db): 
    cache_id = db.test_collection.save({'test': 'some string'}) 
    return cache_id 

def get_cache(db, cache_id): 
    entry = db.test_collection.find_one({'_id' : bson.objectid.ObjectId(cache_id)}) 
    if not entry: 
     print('No entry for %s' % cache_id) 

    return entry 

i = 0 
while 1: 
    i += 1 
    cache_id = set_cache(db) 

    t = threading.Thread(target=get_cache, args=(db, cache_id)) 
    t.start() 
    t.join() 

    if i > 10000: 
     break 

N.