Last active
June 28, 2017 03:31
-
-
Save allenyang79/4f21c501fec098a2abe6febd03a2a465 to your computer and use it in GitHub Desktop.
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
# -*- coding: utf-8 -*- | |
import os | |
try: | |
from gevent import sleep | |
except: | |
from time import sleep | |
class LockFail(Exception): | |
pass | |
class Locker(object): | |
def __init__(self, lockfile, retry=1, timesleep=1.0): | |
"""use physical file to handle lock""" | |
self.lockfile = lockfile | |
self.retry = retry | |
self.timesleep = timesleep | |
def __enter__(self): | |
retry = self.retry | |
last_lock_fail = None | |
while retry > 0: | |
retry -= 1 | |
try: | |
if os.path.exists(self.lockfile): | |
raise LockFail('lockfile: `%s` is existed for another lock.' % self.lockfile) | |
with open(self.lockfile, 'w+') as fp: | |
fp.write(str(os.getpid())) | |
self.last_lock_fail = None | |
break | |
except LockFail as error: | |
self.last_lock_fail = error | |
sleep(self.timesleep) | |
if last_lock_fail: | |
raise last_lock_fail | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
os.remove(self.lockfile) | |
if __name__ == '__main__': | |
import gevent | |
with Locker('testlock', retry=3, timesleep=3) as lock: | |
for i in range(0, 3): | |
print i | |
gevent.sleep(1) |
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
# -*- coding: utf-8 -*- | |
import contextlib | |
import os | |
class LockFail(Exception): | |
pass | |
@contextlib.contextmanager | |
def lock(filepath): | |
"""use physical file to handle lock""" | |
if os.path.exists(filepath): | |
raise LockFail('lockfile: %s is existed for another lock.' % filepath) | |
with open(filepath, 'w+') as fp: | |
fp.write(str(os.getpid())) | |
yield | |
os.remove(filepath) | |
if __name__ == '__main__': | |
import gevent | |
def task(): | |
with lock('locktest'): | |
for i in range(0, 10): | |
gevent.sleep(1) | |
print "sleep", os.getpid() | |
glets = [] | |
for i in range(0, 10): | |
#lock('locktest') | |
glets.append(gevent.spawn(task)) | |
gevent.joinall(glets) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment