def release(self): """Releases the lock, that was acquired with the same object. .. note:: If you want to release a lock that you acquired in a different place you have two choices: * Use ``Lock("name", id=id_from_other_place).release()`` * Use ``Lock("name").reset()`` """ if self._lock_renewal_thread is not None: self._stop_lock_renewer() log_info("Releasing %s." % self._name) error = _eval_script(self._client, UNLOCK_SCRIPT, self._name, self._signal, self._signal_expire, args=(self._id, )) if error == 1: raise NotAcquired( "Lock %s is not acquired or it already expired." % self._name) elif error: raise RuntimeError( "Unsupported error code %s from EXTEND script." % error)
def loop(): identifier1 = str(uuid.uuid1()) conn = redis.Redis(connection_pool=redis_connection.redis_pool) response = conn.client_list() log_info('sbsb' + str(response)) global lock lock = Lock(conn, "my_lock1", expire=10, id=identifier1, auto_renewal=True) val = conn.get("my_lock1") print(str(val)) pid = os.fork() if pid == 0: while True: w1() else: print("Create the process w1") pid = os.fork() identifier2 = str(uuid.uuid1()) print(identifier1 + ":" + identifier2) nlock = Lock(conn, "my_lock1", expire=10, id=identifier2, auto_renewal=True) if pid == 0: while True: w2(nlock) else: print("Create the process w2")
def _eval_script(redis, script_id, *keys, **kwargs): """Tries to call ``EVALSHA`` with the `hash` and then, if it fails, calls regular ``EVAL`` with the `script`. """ args = kwargs.pop('args', ()) if kwargs: raise TypeError("Unexpected keyword arguments %s" % kwargs.keys()) try: return redis.evalsha(SCRIPTS[script_id], len(keys), *keys + args) except NoScriptError: log_info("%s not cached." % SCRIPTS[script_id + 2]) return redis.eval(SCRIPTS[script_id + 1], len(keys), *keys + args)
def _start_lock_renewer(self): """ Starts the lock refresher thread. """ if self._lock_renewal_thread is not None: raise AlreadyStarted("Lock refresh thread already started") log_info("Starting thread to refresh lock every %s seconds" % self._lock_renewal_interval) self._lock_renewal_stop = threading.Event() self._lock_renewal_thread = threading.Thread( group=None, target=self._lock_renewer, kwargs={ 'lockref': weakref.ref(self), 'interval': self._lock_renewal_interval, 'stop': self._lock_renewal_stop }) self._lock_renewal_thread.setDaemon(True) self._lock_renewal_thread.start()
def w1(): global lock if lock._held: log_info('held') if lock.locked(): log_info('lock live') lock.acquire() print("w1 get the lock") print(lock._client.get('lock:my_lock1')) time.sleep(20) if lock._lock_renewal_thread is not None: log_info('fffgggg') if lock._lock_renewal_thread.isAlive(): log_info('renew fail') lock.release() print("w1 end")
def _stop_lock_renewer(self): """ Stop the lock renewer. This signals the renewal thread and waits for its exit. """ if self._lock_renewal_thread is None or not self._lock_renewal_thread.is_alive( ): return log_info("Signalling the lock refresher to stop") self._lock_renewal_stop.set() log_info("wchao") log_info(self._client.get(self._name)) self._lock_renewal_thread.join() self._lock_renewal_thread = None log_info("Lock refresher has stopped")
def _lock_renewer(lockref, interval, stop): """ Renew the lock key in redis every `interval` seconds for as long as `self._lock_renewal_thread.should_exit` is False. """ while True: res = stop.wait(timeout=interval) log_info(res) if res: break log_info("Refreshing lock") lock = lockref() if lock is None: log_info("The lock no longer exists, " "stopping lock refreshing") break lock.extend(expire=lock._expire) del lock log_info("Exit requested, stopping lock refreshing")
def acquire(self, blocking=True, timeout=None): """ :param blocking: Boolean value specifying whether lock should be blocking or not. :param timeout: An integer value specifying the maximum number of seconds to block. """ log_info("Getting %s ..." % self._name) if self._held: raise AlreadyAcquired("Already acquired from this Lock instance.") if not blocking and timeout is not None: raise TimeoutNotUsable("Timeout cannot be used if blocking=False") timeout = timeout if timeout is None else int(timeout) if timeout is not None and timeout <= 0: raise InvalidTimeout( "Timeout (%d) cannot be less than or equal to 0" % timeout) if timeout and self._expire and timeout > self._expire: raise TimeoutTooLarge( "Timeout (%d) cannot be greater than expire (%d)" % (timeout, self._expire)) busy = True blpop_timeout = timeout or self._expire or 0 timed_out = False while busy: busy = not self._client.set( self._name, self._id, nx=True, ex=self._expire) if busy: if timed_out: return False elif blocking: timed_out = not self._client.blpop( self._signal, blpop_timeout) and timeout else: log_info("Failed to get %s." % self._name) return False log_info("Got lock for %s." % self._name) if self._lock_renewal_interval is not None: self._start_lock_renewer() return True
import redis from redis_notes.common.log import log_info def _set_up_redis_instance(): instance = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True) return instance redis_pool = None try: redis_pool = _set_up_redis_instance() print str(redis_pool)+"wwwwww" print redis_pool.ping() response = redis_pool.client_list() log_info('sbsb' + str(response)) log_info(redis_pool) except: print "fail initiating redis instance" try: conn = redis.Redis(host='localhost', port=6379, decode_responses=True) response = conn.client_list() log_info('hbhb'+str(response)) except redis.ConnectionError: log_info('connection sbsbsb')