LMDB报错:lmdb.Error: Attempt to operate on closed/deleted/dropped object.

问题描述:

对LMDB数据库进行写入时,报错:lmdb.Error: Attempt to operate on closed/deleted/dropped object.

原代码:

    env = lmdb.open(path, map_size=1099511627776)
    lib = env.begin(write=True)

    for cur_iter, (inputs, labels) in enumerate(test_loader):
            inputs = inputs.cuda(non_blocking=True)
            labels = labels.cuda()

        # Perform the forward pass.
        preds = model(inputs)
        my_key = get_key()
        my_val = get_val()
        
        lib.put(key=my_key.encode(), value=my_val.encode())
        lib.commit()
	env.close()

错误原因与解决方式

在上述代码中,env.begin()放在了循环以外。每次执行一次lib.commit()之后都会默认close,因此需要重新执行env.begin(),否则在执行第二轮循环时,就会因"Attempt to operate on closed object"而报错。

更正后的代码为:

    env = lmdb.open(path, map_size=1099511627776)
    
    for cur_iter, (inputs, labels) in enumerate(test_loader):
            inputs = inputs.cuda(non_blocking=True)
            labels = labels.cuda()

        # Perform the forward pass.
        preds = model(inputs)
        my_key = get_key()
        my_val = get_val()
        
        lib = env.begin(write=True)
        lib.put(key=my_key.encode(), value=my_val.encode())
        lib.commit()
	env.close()

猜你喜欢

转载自blog.csdn.net/qq_41112170/article/details/129389061