基于condition 实现的线程安全的优先队列(python实现)
2017-10-12 14:28
766 查看
可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。基于此同步原语, 我实现了一个基本简单的线程安全的优先队列:
我还实现了一个基于event 线程安全的优先队列,请看<基于condition 实现的线程安全的优先队列(python实现)>
import heapq import threading # import time class Item: def __init__(self, name): self.name = name def __repr__(self): return 'Item({!r})'.format(self.name) class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 self.mutex = threading.Lock() self.cond = threading.Condition() def push(self, item, priority): self.cond.acquire() heapq.heappush(self._queue, (-priority, self._index, ite 4000 m)) # 存入一个三元组, 默认构造的是小顶堆 self._index += 1 self.cond.notify() # 唤醒一个挂起的线程 self.cond.release() def pop(self): self.cond.acquire() if len(self._queue) == 0: # 当队列中数据的数量为0 的时候, 阻塞线程, 要实现线程安全的容器, 其实不难, 了解相关同步原语的机制, 设计好程序执行时的逻辑顺序(在哪些地方阻塞, 哪些地方唤醒) self.cond.wait() # wait方法释放内部所占用的锁, 同时线程被挂起, 知道接收到通知或超时, 当线程被唤醒并重新占用锁, 程序继续执行下去 else: x = heapq.heappop(self._queue)[-1] # 逆序输出 self.cond.release() return x def test1(p, item, index): for i in range(3): p.push(Item(item), index) def test2(p): for i in range(3): print(p.pop()) if __name__ == '__main__': p = PriorityQueue() t1 = threading.Thread(target=test1, args=(p, 'foo', 1)) t3 = threading.Thread(target=test1, args=(p, 'bar', 2)) t4 = threading.Thread(target=test1, args=(p, 'Ryan', 28)) t2 = threading.Thread(target=test2, args=(p,)) t5 = threading.Thread(target=test2, args=(p,)) t6 = threading.Thread(target=test2, args=(p,)) t1.start() t2.start() t1.join() t2.join() t3.start() t5.start() t3.join() t5.join() t4.start() t6.start() t4.join() t6.join()
我还实现了一个基于event 线程安全的优先队列,请看<基于condition 实现的线程安全的优先队列(python实现)>
相关文章推荐
- 基于condition 实现的线程安全的优先队列(python实现)
- 基于event 实现的线程安全的优先队列(python实现)
- 11.python并发入门(part8 基于线程队列实现生产者消费者模型)
- 用c++11的bind,function,boost::condition_variable实现的一个线程安全的任务队列
- Python 使用list实现无边际优先队列 (基于class, 包含迭代器)
- 这里实现一个基于数组的线程安全的循环队列
- Python 使用由单链表构建的数组实现有边际优先队列 (基于class, 包含迭代器)
- 排序算法之——优先队列经典实现(基于二叉堆)
- 算法基础:排序(四)——二叉堆、优先队列、堆排序——Python实现
- 优雅设计封装基于Okhttp3的网络框架(三):多线程下载功能核心实现 及 线程池、队列机制、终止线程解析
- Python基于list的append和pop方法实现堆栈与队列功能示例
- 基于Spring+Ibatis的安全线程实现
- Java基于堆结构实现优先队列功能示例
- 算法基础:排序(四)——二叉堆、优先队列、堆排序——Python实现
- 基于Lock对象的Condition接口实现的有界队列
- C#实现优先队列 基于二叉堆 附使用案例
- 最小堆实现优先队列:Python实现
- 基于堆的优先队列实现