简体   繁体   中英

global lock causing my program to stop running

Whenever I run part of my program that has a threading.Lock in it, my program stops running altogether (It does not crash, just pauses).

I need this as it is a server and multiple clients may be connecting and trying to overwrite the data all at the same time. At the time of running this, only one thread was active with a client connecting to it. I use this for my Sqlite3 databases too. I have not noticed it causing a problem there, as it seems to run perfectly fine despite the global lock. All are done in the same format of

with global_lock:

Here is where the thread starts alongside how I import the thread

from threading import Thread, Lock
global_lock = Lock()
while True:
    conn, addr = s.accept()
    connThread = Thread(target=handler, args=(conn, addr))
    connThread.daemon = True
    connThread.start()

Here is the program

def addUser_InHash(username, password):

    print("Adding user in hash")
    hashID = 0
    hashString = username + password
    added = False
    for i in hashString:
        hashID += ord(i)
    hashID = hashID % hashKey
    print(hashID, "hashID in addUser")

    file = open("LoginHashTable.pickle", "rb+")
    if os.path.getsize("LoginHashTable.pickle") > 0:
        hashTable = pickle.load(file)
        print("File not empty,\nSaved Data:\n{}".format(hashTable))

    else:
        print("File empty")
        hashTable = {}
    count = 0

    while not added:
        print("while not count :", count)
        count += 1
        if hashID in hashTable:
            # If this index exists
            if hashID > (hashKey - 1):
                hashID = 0
            else:
                hashID += 1
                if hashID > (hashKey - 1):
                    hashID = 0

        else:
            print("User doesnt exist, adding to hash table")
            hashTable[hashID] = [username, password]
            print("New Added")
            print(hashTable)
            added = True

    print("Saving updated file addUser_InHash")

    if hashTable:
        with global_lock:
            file.seek(0)  # Move file pointer back to beginning of file
            file.truncate()  # Empty file by truncating to current file pointer position
            pickle.dump(hashTable, file)
            print(hashTable)
            print("Data saved")
            file.close()
    else:
        print("Hash table still empty, addUser_InHash")


def deleteUser_InHash(username, password):


    print("In deleteUser_InHash\nUsername: {}\nPassword: {}".format(username,password))
    dataFound = True
    hashID = 0
    count = 0
    hashString = username + password

    if os.path.getsize("LoginHashTable.pickle") > 0:
        file = open("LoginHashTable.pickle", "rb+")
        hashTable = pickle.load(file)
        print("File not empty,\nSaved Data:\n{}".format(hashTable))

    else:
        print("File empty")
        dataFound = False

    if dataFound:
        print("datafound true")
        for i in hashString:
            hashID += ord(i)
        hashID = hashID % hashKey
        print("hashID:",hashID)
        try:
            print("In try")
            while dataFound:
                print("In while, count:",count)
                if count == hashKey:
                    dataFound = False
                if hashTable[hashID] == [username,password]:
                    del hashTable[hashID]
                    print("Outside global lock")
                    with global_lock:
                        print("Inside global lock")
                        file.seek(0)  # Move file pointer back to beginning of file
                        file.truncate()  # Empty file by truncating to current file pointer position
                        pickle.dump(hashTable, file)
                        print(hashTable)
                        print("Data saved")
                        file.close()
                    print("Outside global lock")
                    print("Data updated")
                    print("User :", username, "deleted")
                    break
                else:
                    hashID += 1
                count += 1

        except IndexError:
            print("username could not be found")
            return False

    else:
        return False

The two functions are called in this sequence:

deleteUser_InHash(username1,password1)
addUser_InHash(username2,password2)

The with global lock works fine in deleteUser_InHash() function but stops the program in addUser_InHash() .

The program hangs here:

{33: ['foo', 'bar'], 0: ['toni', 'tony'], 34: ['bar', 'foo'], 118: ['fo', 'la'], 8: ['Tom', 'Tom'], 262: ['Kam', 'Kam'], 258: ['yes', 'no']}
Saving updated file addUser_InHash

Hanging on the line the piece of code:

if hashTable:
    with global_lock:

I know this is true as it never gets to the print statements:

print(hashTable)
print("Data saved")

Inside "addUser_InHash()"

Note to all: I changed

global_lock = Lock()

to

global_lock = RLock()

and now my program is running fine, I believe it has something to do with the fact that RLock allows threads to re-acquire a lock more than once, whilst it seems that normal locks cannot?

Source:https://docs.python.org/3/library/threading.html#thread-objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM