防止线程饥饿 Python

prevent thread starvation Python

我有一些功能可以写一些文件。信号量用于将线程数限制为 2。线程总数为 3。如何防止 3 个线程饥饿?队列是一个选项吗?

import time
import threading

sema = threading.Semaphore(2)


def write_file(file,data):
    sema.acquire()
    try:
        f=open(file,"a")
        f.write(data)
        f.close()
    finally:
        sema.release()

如果一个线程正在等待获取信号量,则其他两个线程中的任何一个都将完成写入并释放信号量。

如果你担心如果有大量的写入,写入者可能会在通知等待线程之前重新获取信号量。我认为这不可能发生。

Semaphore object in Python (2.7) uses a Condition. The Condition adds waiting threads (actually a lock, which the waiting thread is blocking on) to the end of an waiters list and when notifying threads, the notified threads are taken from the beginning of the list。所以这个列表就像一个 FIFO 队列。

看起来像这样:

def wait(self, timeout=None):
    self.__waiters.append(waiter)
    ...

def notify(self, n=1):
    ...
    waiters = self.__waiters[:n]
    for waiter in waiters:
        waiter.release()
    ...

我在阅读 source code 后的理解是 Python 的信号量是 FIFO。我找不到关于此的任何其他信息,所以如果我错了,请纠正我。

我不得不反对接受的问题。 Condition 确实对 wait 进行了排队,但更重要的部分是当它尝试 acquire the Condition lock.

释放线程的顺序是not deterministic

The implementation may pick one at random, so the order in which blocked threads are awakened should not be relied on.

在三个线程的情况下,我同意,两个线程同时尝试获取锁的可能性很小(一个工作,一个在 wait,一个获取锁),但是可能还是有干扰。

对于您的问题,IMO 的一个很好的解决方案是一个线程,它的唯一目的是从队列中读取数据并将其写入文件。所有其他线程都可以写入队列并继续工作。