【问题标题】:Adaptive Mutex in PythonPython中的自适应互斥锁
【发布时间】:2018-02-26 21:14:56
【问题描述】:

有人知道如何在 python 中编写混合互斥锁吗?

我所说的混合互斥锁是指兼具两者的互斥锁:它会旋转一段时间以期待快速锁定,但如果事情花费太长时间,最终会阻塞线程,从而放弃 CPU。

我知道人们已经在 C 中尝试过它,但我正在寻找一种 Python 的方式来实现它。 例如:https://hackernoon.com/building-a-c-hybrid-spin-mutex-f98de535b4ac

【问题讨论】:

    标签: python multithreading python-3.x python-2.7 concurrency


    【解决方案1】:
    class hybridSpinLock:
    def __init__(self):
        self.lock_var = threading.Lock()
        self.threshold = 1
    def lock(self):
        #stalling
        start = time.time()
        elapsed = 0
        while (self.lock_var.acquire(False)==False):
            elapsed = time.time() - start
            if elapsed >= 2*self.threshold:
                self.lock_var.acquire()  # blocking lock
                break
        #update the threshold value
        self.threshold += (elapsed - self.threshold)/8
    def release(self):
        self.threshold=1
        self.lock_var.release()
    

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 2012-06-05
      • 2010-09-16
      • 1970-01-01
      • 2010-12-17
      相关资源
      最近更新 更多