Advertisement
the-technoholik

Non Blocking Monitor in Python

Nov 8th, 2014
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from threading import Lock
  5.  
  6. class NonBlockingMonitor:
  7.     lock = Lock()
  8.  
  9.     def __init__(self):
  10.         pass
  11.  
  12.     def do(self, method):
  13.         """This method does not wait on the resource. If it's available it does
  14.        the action and returns True,
  15.        otherwise it returns False without doing anything.
  16.  
  17.        Params:
  18.            method      the method that must be called if no other thread
  19.                        managed to acquire the lock."""
  20.         if self.lock.acquire(False): # False for non blocking
  21.             ret = method()
  22.             self.lock.release()
  23.             return ret
  24.         else:
  25.             return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement