Exemple #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()  # 开枪(唤醒所有线程)
Exemple #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()
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)
Exemple #4
0
 def __init__(self):
     self.con = Condition()  # 条件变量
Exemple #5
0
from multiprocessing.dummy import Pool as ThreadPool, Condition

s_list = []
con = Condition()


def Shop(i):
    global con
    global s_list
    # 加锁保护共享资源
    for x in range(5):
        with con:
            s_list.append(x)
            print(f"[生产者{i}]生产商品{x}")
            con.notify_all()  # 通知消费者有货了


def User(i):
    global con
    global s_list
    while True:
        with con:
            if s_list:
                print(f"列表商品:{s_list}")
                name = s_list.pop()  # 消费商品
                print(f"[消费者{i}]消费商品{name}")
                print(f"列表剩余:{s_list}")
            else:
                con.wait()

 def __init__(self):
     self.__h_list = []
     self.__con = Condition()  # 条件变量
     self.__index = 0  # 索引