Home >Backend Development >Python Tutorial >How to use condition variables in Python threads

How to use condition variables in Python threads

不言
不言Original
2018-09-11 16:03:592228browse

This article brings you the content about the usage of condition variables in Python threads. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Condition variable is a synchronization primitive built on another lock. This lock will be used when the thread needs to pay attention to a specific state change or event. The typical usage is the producer and consumer problem, in which the data produced by one thread is provided to another thread.

Syntax:

c=Condition(lock)
穿件新的条件变量。lock时可选的Lock或RLock的实例。如果未提供lock参数,就会创建新的RLock实例供条件变量使用。

Common methods:

c.acquire(*args):获取底层锁。此方法将调用底层锁上对应的acquire(*args)方法。

c.release():释放底层锁。此方法将调用底层锁上对应的release()方法

c.wait(timeout):等待直到获取通知或出现超时为止。此方法在调用线程已经获取锁之后调用。
调用时,将释放底层锁,而且线程将进入睡眠状态,直到另一个线程在条件变量上执行notify()或notify_all()方法将其唤醒为止。
在线程被唤醒后,线程讲重新获取锁,方法也会返回。timeout是浮点数,单位为秒。
如果超时,线程将被唤醒,重新获取锁,而控制将被返回。

c.notify(n):唤醒一个或多个等待此条件变量的线程。此方法只会在调用线程已经获取锁之后调用,
而且如果没有正在等待的线程,它就什么也不做。
n指定要唤醒的线程数量,默认为1.被唤醒的线程在它们重新获取锁之前不会从wait()调用返回。

c.notify_all():唤醒所有等待此条件的线程。

Instance template: using condition variables

#条件变量实例
from threading import Condition

c=Condition()
def producer():
    while True:
        c.acquire()
        #生产东西
        ...
        c.notify()
        c.release()

def consumer():
    while True:
        c.acquire()
        while 没有可用的东西:
            c.wait()#等待出现
        c.release()
        #使用生产的东西
        ...

Note: If there are multiple threads waiting for the same condition, The notify() operation will wake up one or more of them (this behavior depends on the underlying operating system). Therefore, there is always the possibility that after a thread wakes up, it discovers that the condition it was waiting for no longer exists. This explains why a while loop is used in the consumer function. If the thread wakes up but the generated item has disappeared, it It will go back and wait for the next signal.

Related recommendations:

10 recommended articles about condition variables and threads

A brief analysis of Python multi-threading Variable problem

The above is the detailed content of How to use condition variables in Python threads. For more information, please follow other related articles on the PHP Chinese website!

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