Home  >  Article  >  Backend Development  >  Detailed explanation of the Python version of read-write lock operation method

Detailed explanation of the Python version of read-write lock operation method

高洛峰
高洛峰Original
2017-03-06 13:49:532133browse

The example in this article describes the python version of the read-write lock operation method. I share it with you for your reference. The details are as follows:

The read-write lock mechanism has been used recently, but it is not included in the built-in library of python2.7.
Talk about read-write locks online There are many examples, but the principle is simple and the code is clear but not many, so just write one yourself.

Read-write locks are generally used when multiple readers, one or more writers access a certain resource at the same time when. Resources can be shared between multiple readers, but resources are mutually exclusive between writers and readers, and between writers and writers.

This means that there can be multiple readers or one writer working at the same time.

Broken down, read-write locks can be divided into three categories, reader priority, writer priority and public strategy.

The first one is readers first.
The purpose is to ensure that readers can obtain resources without waiting as much as possible.
The key points of implementation are relatively simple for writers. Only one lock is needed to control whether it can be written.
In terms of readers, writers should be blocked when the first reader arrives, and writers should be opened after the last reader leaves. There is a problem with the reader counter. This counter needs to be shared among readers, so an additional lock is needed to ensure the atomicity of the addition and subtraction operations of the counter.

Implementation code:

Define a class RWLock and do simple initialization

import threading
class RWLock(object):
  def __init__(self):
    self.rlock = threading.Lock()
    self.wlock = threading.Lock()
    self.reader = 0

Writer Lock

def write_acquire(self):
  self.wlock.acquire()
def write_release(self):
  self.wlock.release()

Reader Lock

##

def read_acquire(self):
  self.rlock.acquire()
  self.reader += 1
  if self.reader == 1:
    self.wlock.aquire()
  self.rlock.release()
def read_release(self):
  self.rlock.acquire()
  self.reader -= 1
  if self.reader == 0:
    self.wlock.release()
  self.rlock.release()

More For more detailed explanations of the Python version of the read-write lock operation method, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn