Home > Backend Development > Python Tutorial > How to switch threads in python

How to switch threads in python

anonymity
Release: 2019-06-20 14:23:02
Original
4470 people have browsed it

The condition object allows a thread A to stop and wait for other thread B. After thread B meets a certain condition, thread B notifies thread A to continue running. The thread first acquires a condition variable lock. If the condition is insufficient, the thread waits and releases the condition variable lock. If it is satisfied, the thread is executed, and other threads in the wait state can also be notified. Other threads in the wait state will re-judge the conditions after receiving the notification.

How to switch threads in python

The following is an interesting example

import threading
class Boy(threading.Thread):
    def __init__(self, cond, name):
        super(Boy, self).__init__()
        self.cond = cond
        self.name = name
    def run(self):
        self.cond.acquire()
        print(self.name + ": 嫁给我吧!?")
        self.cond.notify()  # 唤醒一个挂起的线程,让hanmeimei表态
        self.cond.wait()  # 释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时,等待hanmeimei回答
        print(self.name + ": 我单下跪,送上戒指!")
        self.cond.notify()
        self.cond.wait()
        print(self.name + ": Li太太,你的选择太明治了。")
        self.cond.release()
class Girl(threading.Thread):
    def __init__(self, cond, name):
        super(Girl, self).__init__()
        self.cond = cond
        self.name = name
    def run(self):
        self.cond.acquire()
        self.cond.wait()  # 等待Lilei求婚
        print(self.name + ": 没有情调,不够浪漫,不答应")
        self.cond.notify()
        self.cond.wait()
        print(self.name + ": 好吧,答应你了")
        self.cond.notify()
        self.cond.release()
cond = threading.Condition()
boy = Boy(cond, "LiLei")
girl = Girl(cond, "HanMeiMei")
girl.start()
boy.start()
Copy after login

The running results are as follows:

LiLei: 嫁给我吧!?
HanMeiMei: 没有情调,不够浪漫,不答应
LiLei: 我单下跪,送上戒指!
HanMeiMei: 好吧,答应你了
LiLei: Li太太,你的选择太明治了。
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template