SoFunction
Updated on 2024-11-18

Python Multi-threaded Advanced Lock Condition Simple Usage Example

This article example describes the simple usage of python multithreaded advanced lock condition. Shared for your reference, as follows:

In multi-threaded programming, if you use a condition object instead of a lock, you can realize that the data will be processed only after an event is triggered, and the condition contains the following methods.

  • - wait: the thread hangs and continues to run when it receives a notify.
  • - notify: notify other threads, release other threads from the wai state.
  • - notifyAll(): Notifies all threads of a notification.
  • - acquire and release: acquiring and releasing locks, similar to lock.
  • - enter and exit enable the object to support contextual operations.
  def __enter__(self):
    return self._lock.__enter__()
  def __exit__(self, *args):
    return self._lock.__exit__(*args)

Code.

import threading
from threading import Condition
# condition
class XiaoAi():
  def __init__(self, cond):
     = cond
    super().__init__(name="xiaoai")
  def run(self):
    ()
    ()
    print('{}:ennn. '.format())
    ()
    ()
    print('{}:(coll.) well, good.. '.format())
    ()
class TianMao():
  def __init__(self, cond):
    super().__init__(name="tiaomao")
     = cond
  def run(self):
    ()
    print('{}:hello ~ xiaoai. '.format())
    ()
    ()
    print('{}:Let's read a poem.! . '.format())
    ()
    ()
if __name__ == '__main__':
  condition = Condition()
  xiaoai = XiaoAi(condition)
  tianmao = TianMao(condition)
  # The startup sequence is important
  ()
  ()

Print Results.

tiaomao:hello ~ xiaoai.
xiaoai:ennn.
tiaomao:Let's read a poem! .
xiaoai:ok ta

Summary.

This one's a bit of an underdog.

Readers interested in more Python related content can check out this site's topic: theSummary of Python process and thread manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorials》、《Python + MySQL Database Programming Tutorial for Beginnersand theSummary of common database manipulation techniques in Python

I hope that what I have said in this article will help you in Python programming.