Example #1
0
class CountDownLatch(object):
    def __init__(self):
        self.con = Condition()  # 条件变量

    def wait(self):
        with self.con:
            self.con.wait()

    def countDown(self):
        with self.con:
            self.con.notify_all()  # 开枪(唤醒所有线程)
Example #2
0
def run(
    input_image: Array,
    new_input_image: Condition,
    input_size: (int, int),
    output_image: Array,
    new_output_image: Condition,
    output_size: (int, int),
):
    while True:
        with new_input_image:
            new_input_image.wait()

        with input_image.get_lock():
            image = Image.frombuffer("RGB", input_size, input_image.get_obj())
            result = image.resize(output_size, resample=Image.NEAREST)

        with output_image.get_lock():
            dest = numpy.frombuffer(output_image.get_obj(), dtype=numpy.uint8).reshape(
                (output_size[0], output_size[1], 3)
            )
            numpy.copyto(dest, numpy.array(result))

        with new_output_image:
            new_output_image.notify_all()
Example #3
0
class MaxPriorityQueue(object):
    """自定义一个最大优先队列"""
    def __init__(self):
        self.__h_list = []
        self.__con = Condition()  # 条件变量
        self.__index = 0  # 索引

    def put(self, value, sort=0):
        with self.__con:
            # heapq是最小二叉堆,优先级取负就是最大二叉堆了
            heapq.heappush(self.__h_list, (-sort, self.__index, value))
            self.__index += 1
            self.__con.notify()  # 随机通知一个阻塞等的线程

    def get(self):
        with self.__con:
            while 1:
                # 0 => False
                if not self.qsize():
                    self.__con.wait()  # 列表为空则阻塞等
                return heapq.heappop(self.__h_list)[-1]  # 返回元组最后一个元素(value)

    def qsize(self):
        return len(self.__h_list)