Python distributed locks

Source: Internet
Author: User
In order to avoid repeated computations, the distributed lock service can be used in some time-consuming queries.
At the same time only one operation is in progress, the same kind of operation is waiting to retry.
The following code (FETCH_WITH_DIST_LOCK) defines a fetcher, a updater.
If Fetcher gets no data, it is updated with updater. After the update succeeds, the result is returned by Fetcher.
There are also cases where we want to update only one data, the update is multiple, but the update operation is not atomic.
We'll go through the update_with_dist_lock.

def fetch_with_dist_lock (Mc_store, Mutex_key, Fetcher, Updater, lock_time=3*60*1000, sleep_time=100 , retry_times=3): i = 0 while I < retry_times:i + = 1 need_update, results = fetcher () if NE                    Ed_update:if (Mc_store.add (Mutex_key, Lock_time)): Try:updater () Continue finally: #release the distribute mutex anyway Mc_sto Re.delete (Mutex_key) else:time.sleep ((sleep_time*1.0)/1000) Continue Retu    RN Results #too much tries, but failed still. return Nonedef F_wrapper (f, *args, **kwargs): def _ (): Return F (*args, **kwargs) return _def update_with_dist _lock (Mc_store, Mutex_key, Updater, lock_time=60*1000, sleep_time=100, retry_times=5): i = 0 while I < Retry_time              S:i + = 1 if (Mc_store.add (Mutex_key, Lock_time)): try:  Updater () return True finally:mc_store.delete (mutex_key) Else: Time.sleep ((sleep_time*1.0)/1000) Continue return False
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.