search
HomeBackend DevelopmentPython TutorialExamples of using four types of locks in Python (code)

The content of this article is about the usage examples (code) of the four locks in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Lock mutex

Before use

num = 0
def a():
    global num
    for _ in range(10000000):
        num += 1

def b():
    global num
    for _ in range(10000000):
        num += 1
if __name__ == '__main__':
    t1=Thread(target=a)
    t1.start()
    t2=Thread(target=b)
    t2.start()
    t1.join()
    t2.join()
    print(num)    #基本永远会小于20000000

After use

num = 0
def a(lock):
    global num
    for _ in range(1000000):
        with lock:
            num += 1
def b(lock):
    global num
    for _ in range(1000000):
        with lock:
            num += 1
if __name__ == '__main__':
    lock = threading.Lock()
    t1=Thread(target=a, args=(lock,))
    t1.start()
    t2=Thread(target=b, args=(lock,))
    t2.start()
    t1.join()
    t2.join()
    print(num)    #永远会输出20000000

RLock reuse lock

#在之前的代码中永远不可能出现锁在没释放之前重新获得锁,但rlock可以做到,但只能发生在一个线程中,如:
num = 0
def a(lock):
    with lock:
        print("我是A")
        b(lock)
def b(lock):
    with lock:
        print("我是b")
if __name__ == '__main__':
    lock = threading.Lock()
    t1 = Thread(target=a, args=(lock,))
    t1.start()    #会发生死锁,因为在第一次还没释放锁后,b就准备上锁,并阻止a释放锁

After use

if __name__ == '__main__':
    lock = threading.RLock()    #只需要改变锁为RLock程序马上恢复
    t1 = Thread(target=a, args=(lock,))
    t1.start()

Condition synchronization lock

#这个程序我们模拟甲乙对话
Jlist = ["在吗", "干啥呢", "去玩儿不", "好吧"]
Ylist = ["在呀", "玩儿手机", "不去"]
def J(list):
    for i in list:
        print(i)
        time.sleep(0.1)
def Y(list):
    for i in list:
        print(i)
        time.sleep(0.1)
if __name__ == '__main__':
    t1 = Thread(target=J, args=(Jlist,))
    t1.start()
    t1.join()
    t2 = Thread(target=Y, args=(Ylist,))
    t2.start()
    t2.join()    #上面的程序输出后发现效果就是咱们想要的,但是我们每次输出后都要等待0.1秒,也无法正好确定可以拿到时间片的最短时间值,并且不能保证每次正好都是另一个线程执行。因此,我们用以下方式,完美解决这些问题。

After use

Jlist = ["在吗", "干啥呢", "去玩儿不", "好吧"]
Ylist = ["在呀", "玩儿手机", "不去","哦"]
def J(cond, list):
    for i in list:
        with cond:
            print(i)
            cond.notify()
            cond.wait()
def Y(cond, list):
    for i in list:
        with cond:
            cond.wait()
            print(i)
            cond.notify()
if __name__ == '__main__':
    cond = threading.Condition()
    t1 = Thread(target=J, args=(cond, Jlist))
    t2 = Thread(target=Y, args=(cond, Ylist))
    t2.start()
    t1.start()    #一定保证t1启动在t2之后,因为notify发送的信号要被t2接受到,如果t1先启动,会发生阻塞。

Seamplore semaphore
Before use

class B(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name
    def run(self):
        time.sleep(1)
        print(self.name)
class A(threading.Thread):
    def __init__(self):
        super().__init__()
    def run(self):
        for i in range(100):
            b = B(i)
            b.start()
if __name__ == '__main__':
    a = A()
    a.start()    #执行后发现不断在输出

After use

class B(threading.Thread):
    def __init__(self, name, sem):
        super().__init__()
        self.name = name
        self.sem = sem
    def run(self):
        time.sleep(1)
        print(self.name)
        sem.release()
class A(threading.Thread):
    def __init__(self, sem):
        super().__init__()
        self.sem = sem
    def run(self):
        for i in range(100):
            self.sem.acquire()
            b = B(i, self.sem)
            b.start()
if __name__ == '__main__':
    sem = threading.Semaphore(value=3)
    a = A(sem)
    a.start()    #通过执行上面的代码,我们发现一次只能输出三个数字,sem控制访问并发量

The above is the detailed content of Examples of using four types of locks in Python (code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

What is the purpose of using arrays when lists exist in Python?What is the purpose of using arrays when lists exist in Python?May 01, 2025 am 12:04 AM

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

Explain how to iterate through the elements of a list and an array.Explain how to iterate through the elements of a list and an array.May 01, 2025 am 12:01 AM

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function