Python同步

2024-05-16 02:03:08 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试使用Python创建同步数据库调用。我正在实现一个读写器解决方案,以便多个线程可以同时从数据库中读取数据,或者多个线程可以同时向数据库中写入数据

我想我的代码有一个死锁问题,但我不知道如何解决它。当运行我的程序时,一切都开始良好,但在多次写入后,发生了几次读取,然后程序冻结。没有发生写入或读取操作

from threading import *

mutex = RLock() # RLock so only one thread can lock and unlock
global read_count, writer_count # Keep track of number of reading and writting threads
read_lock = Lock() # Updated 
write_lock = Lock() # Updated  # Initialize the locks
read_count = 0 # Updated 
writer_count = 0 # Updated 

 def read_from_db(self, sql):
        mutex.acquire()
        global read_count, writer_count
        if writer_count > 0:
            mutex.release() #release mutex to avoid deadlock
            read_lock.acquire() # Get the read_lock or wait until able to get it
        else:
            mutex.release()

        mutex.acquire()
        if read_count == 0:
            write_lock.acquire() # Get the write lock so writers can't get it while read thread is reading

        read_count += 1
        mutex.release()

        # read from DB 

        mutex.acquire()
        read_count -= 1
        if read_count <= 0:
            write_lock.release() #release the write lock
        mutex.release()

    def write_to_db(self):
        global read_count, writer_count

        mutex.acquire()
        if read_count > 0:
            mutex.release() #release mutex to avoid deadlock
            write_lock.acquire() #get the write lock or wait until able to get it
        else:
            mutex.release()

        mutex.acquire()
        if writer_count <= 0:
            read_lock.acquire() #Get the read_lock so that no reads happen while writing 

        writer_count += 1
        mutex.release()

        # write to db

        mutex.acquire()
        writer_count -= 1
        if writer_count == 0: # Updated 
            read_lock.release()
        mutex.release()

Tags: thetofrom数据库lockreadgetrelease