Tianyang Li
Tianyang Li

Reputation: 1785

Is shelve in Python thread safe?

Is shelve in Python used for data persistence thread safe? If not, what's a good alternative?

Upvotes: 12

Views: 5333

Answers (3)

AndrewE
AndrewE

Reputation: 35

Threads = # amount of threads

thread_moment = [False for _ in range(Threads)] 

def job(x):  # x would be the index of the thread  

    lock.aquire()

    # open/edit/update/close your shelve file

    thread_moment[x] = True 

    lock.release()

    while True:
        if all(thread_moment) == True:
            thread_moment = [False for _ in range(threads)]
            break
        else:
            time.sleep(1)

    # carry on with your script

Upvotes: -1

Mahmoud Abdelkader
Mahmoud Abdelkader

Reputation: 24939

From the standard library documentation about the Shelve module, under the heading Restrictions:

The shelve module does not support concurrent read/write access to shelved objects. (Multiple simultaneous read accesses are safe.)

I would assume that it's probably implementation dependent and in which case, in order to be sure, I would conclude that it certainly is not thread safe.

Upvotes: 14

user2665694
user2665694

Reputation:

Alternatives: ZODB

http://www.zodb.org/

Upvotes: 3

Related Questions