Created
March 28, 2022 02:47
-
-
Save JoseitoOliveira/718951b693c198e35493525e9cced55a to your computer and use it in GitHub Desktop.
Classe que implementa uma mutex com níveis de prioridade.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threading import Lock, Thread | |
class PriorityLock: | |
def __init__(self): | |
self._main_lock = Lock() | |
self.priorities = [] | |
def acquire(self, priority): | |
assert priority >= 0 | |
self.priorities.append(priority) | |
while True: | |
self._main_lock.acquire() | |
if priority == max(self.priorities): | |
self.priorities.remove(priority) | |
return | |
self._main_lock.release() | |
def release(self): | |
self._main_lock.release() | |
if __name__ == '__main__': | |
from functools import partial | |
def test(priority, lock): | |
for _ in range(20): | |
lock.acquire(priority) | |
print(f'{priority} acquired') | |
lock.release() | |
lock = PriorityLock() | |
threadA = Thread(target=partial(test, 1, lock)) | |
threadA.start() | |
threadC = Thread(target=partial(test, 3, lock)) | |
threadC.start() | |
threadB = Thread(target=partial(test, 2, lock)) | |
threadB.start() | |
threadD = Thread(target=partial(test, 4, lock)) | |
threadD.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment