Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Last active June 28, 2017 03:31
Show Gist options
  • Save allenyang79/4f21c501fec098a2abe6febd03a2a465 to your computer and use it in GitHub Desktop.
Save allenyang79/4f21c501fec098a2abe6febd03a2a465 to your computer and use it in GitHub Desktop.
# -*- 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)
# -*- 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