Created
December 5, 2018 14:23
-
-
Save celebdor/f43a6e20c30465d86bf877cdebc5366f to your computer and use it in GitHub Desktop.
example of a file locking decorator
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
| import datetime | |
| import fcntl | |
| from multiprocessing import Process | |
| from os import path | |
| import tempfile | |
| import time | |
| def run_exclusive(filename): | |
| def wrapper(func): | |
| def inner_wrapper(*args, **kwargs): | |
| with open(filename, 'a') as lockfile: | |
| fcntl.lockf(lockfile, fcntl.LOCK_EX) | |
| print(datetime.datetime.now(), 'Lock acquired by', func.__name__) | |
| result = func(*args, **kwargs) | |
| print(datetime.datetime.now(), 'Lock released by', func.__name__) | |
| fcntl.lockf(lockfile, fcntl.LOCK_UN) | |
| return result | |
| return inner_wrapper | |
| return wrapper | |
| # Usage: | |
| tmpdir = tempfile.mkdtemp() | |
| @run_exclusive(path.join(tmpdir, 'tonilock')) | |
| def waitprint(name): | |
| time.sleep(2) | |
| print('wait', name) | |
| @run_exclusive(path.join(tmpdir, 'tonilock')) | |
| def nowaitprint(name): | |
| print('nowait', name) | |
| if __name__ == '__main__': | |
| Process(target=waitprint, args=('hello',)).start() | |
| Process(target=nowaitprint, args=('hello',)).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment