如何在线程间进行事件通知python

#如何在线程间进行事件通知
#实现一个打包线程,将转换出的xml文件压缩打包,比如转换线程每生产出100个xml文件,
# 就通知打包线程将他们打包成一个xxx.tgz文件,并删除xml文件,打包完成后,
# 打包线程反过来通知转换线程,转换线程继续转换。
import tarfile
import os

def tarXML(tfname):
   tf=tarfile.open(tfname,'w:gz')
   for fname in os.listdir('.'):
        if  fname.endswith('.xml'):
            tf.add(fname)
            os.remove(fname)
   tf.close()
   if not tf.members:
       os.remove(tfname)
tarXML('test.tgz')

import tarfile
import os

class TarThread(Thread):
    def __init__(self,cEvent,tEvent):
        Thread.__init__(self)
        self.count=0
        self.cEvent=cEvent
        self.tEvent = tEvent
    def tarXML(self,tfname):
       self.count +=1
       tfname='%d.tgz' % self.count
       tf=tarfile.open(tfname,'w:gz')
       for fname in os.listdir('.'):
            if  fname.endswith('.xml'):
                tf.add(fname)
                os.remove(fname)
       tf.close()
       if not tf.members:
           os.remove(tfname)
    #线程间的事件通知,可以使用标准库中的Threading.Event:
    # 1.等待事件一端调用wait,等待事件
    # 2.通知事件一端调用set,通知事件
    """
    from threading import Event,Thread
    def f(e):
       print 'f 0'
       e.wait()
       print'f 1'
    e=Event()
    t=Thread(target=f,args=(e,))
    t.start()
    """
    def run(self):
          while True:
            self.cEvent.wait()#等待对方转换完毕
            self.tarXML()
            self.cEvent.clear()#为了重复使用事件n
            self.tEvent.set()
tarXML('test.tgz')

猜你喜欢

转载自blog.csdn.net/weixin_38858860/article/details/89091526