Home > Backend Development > Python Tutorial > Python多线程编程(八):使用Event实现线程间通信

Python多线程编程(八):使用Event实现线程间通信

WBOY
Release: 2016-06-10 15:16:12
Original
1651 people have browsed it

使用threading.Event可以实现线程间相互通信,之前的Python:使用threading模块实现多线程编程七[使用Condition实现复杂同步]我们已经初步实现了线程间通信的基本功能,但是更为通用的一种做法是使用threading.Event对象。使用threading.Event可以使一个线程等待其他线程的通知,我们把这个Event传递到线程对象中,Event默认内置了一个标志,初始值为False。一旦该线程通过wait()方法进入等待状态,直到另一个线程调用该Event的set()方法将内置标志设置为True时,该Event会通知所有等待状态的线程恢复运行。

复制代码 代码如下:

'''
Created on 2012-9-9
 
@author: walfred
@module: thread.TreadTest8
''' 
 
import threading 
import time 
 
class MyThread(threading.Thread): 
    def __init__(self, signal): 
        threading.Thread.__init__(self) 
        self.singal = signal 
 
    def run(self): 
        print "I am %s,I will sleep ..."%self.name 
        self.singal.wait() 
        print "I am %s, I awake..." %self.name 
 
if __name__ == "__main__": 
    singal = threading.Event() 
    for t in range(0, 3): 
        thread = MyThread(singal) 
        thread.start() 
 
    print "main thread sleep 3 seconds... " 
    time.sleep(3) 
 
    singal.set()

运行效果如下:

复制代码 代码如下:

I am Thread-1,I will sleep ...
I am Thread-2,I will sleep ...
I am Thread-3,I will sleep ...
main thread sleep 3 seconds...
I am Thread-1, I awake...I am Thread-2, I awake...
 
I am Thread-3, I awake...
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