当前位置: 首页>>代码示例>>Python>>正文


Python Event.clear方法代码示例

本文整理汇总了Python中multiprocessing.Event.clear方法的典型用法代码示例。如果您正苦于以下问题:Python Event.clear方法的具体用法?Python Event.clear怎么用?Python Event.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在multiprocessing.Event的用法示例。


在下文中一共展示了Event.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: BroadcastClient

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class BroadcastClient(Process):
    def __init__(self, port, datagram_size, name="BroadcastClient"):
        Process.__init__(self, name=name)
        self.logger = multiprocessing.get_logger()
        self.event = Event()
        self.port = port
        self.datagram_size = datagram_size
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.settimeout(1)
        self.sock.bind(("", self.port))

    def run(self):
        self.event.set()
        self.logger.debug("PID: %d" % multiprocessing.current_process().pid)
        while self.event.is_set():
            try:
                message, (ip, port) = self.sock.recvfrom(self.datagram_size)
                teacher_discovered.send(sender=self)
                self.logger.debug("Received: %s from: %s" % (message, ip))
            except socket.timeout:
                self.logger.debug("%s timeout" % multiprocessing.current_process().name)
            time.sleep(1)

    def stop(self):
        self.logger.debug("Client will halt.")
        self.event.clear()
        self.sock.close()
        self.terminate()
开发者ID:jg19,项目名称:playground,代码行数:31,代码来源:__init__.py

示例2: Logger

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class Logger(object):
    def __init__(self, filename):
        self.qtag = Queue()
        self.done = Event()
        self.tag = None
        self.filename = filename
        self.file = None
    def start(self):
        self.file = open(self.filename, 'w')
        print 'Opened',self.filename,'for writing.'
    def set_tag(self, tag):
        self.qtag.put(tag)
    def set_done(self):
        self.done.set()
    def log(self, nodeid, msgid, data):
        if not self.qtag.empty():
            self.tag = self.qtag.get()
        if self.done.is_set():
            self.done.clear()
            return True
        L = ['%f'%time.time(), '%d'%nodeid, '%d'%msgid] + map(str,data)
        if self.tag:
            L.append(self.tag)
        print >>self.file, ','.join(L)
        self.file.flush()
    def close(self):
        if self.file:
            self.file.close()
            print 'File closed.'
开发者ID:malloch,项目名称:emergeData,代码行数:31,代码来源:gesture_recorder.py

示例3: TestProxyData

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class TestProxyData(TestData):

    def setup(self):
        create_link('dummyX', 'dummy')
        t_url = 'unix://\0%s' % (uuid.uuid4())
        p_url = 'unix://\0%s' % (uuid.uuid4())
        self.connect = Event()
        self.release = Event()

        target = Process(target=_run_remote_uplink,
                         args=(t_url, self.connect, self.release))
        target.daemon = True
        target.start()
        self.connect.wait()
        self.connect.clear()

        proxy = Process(target=_run_remote_uplink,
                        args=(p_url, self.connect, self.release))
        proxy.daemon = True
        proxy.start()
        self.connect.wait()
        self.connect.clear()

        self.ip = IPRoute(do_connect=False)
        link, proxy = self.ip.connect(p_url)
        self.ip.register('bala', proxy)
        link, host = self.ip.connect(t_url, addr=proxy)
        service = self.ip.discover(self.ip.default_target, addr=host)

        self.ip.default_peer = host
        self.ip.default_dport = service

        self.dev = self.ip.link_lookup(ifname='dummyX')
开发者ID:chantra,项目名称:pyroute2,代码行数:35,代码来源:test_ipr.py

示例4: SharedFile

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class SharedFile(object):
    def __init__(self, filename):
        self.filename = filename
        self.fevent = Event()
        # self.state = Value('i', 0)
        self.fevent.set()

    def write(self, mode, data):
        # print("Write {}".format(inspect.stack()[1][3]))
        self.wait_freedom_and_lock()

        f = open(self.filename, mode)
        f.write(data)
        f.close
        self.unlock()

    def read(self):
        # print("Read {}".format(inspect.stack()[1][3]))
        self.wait_freedom_and_lock()

        f = open(self.filename, 'r')
        data = f.read()
        f.close
        self.unlock()
        return data

    def wait_freedom_and_lock(self):
        self.fevent.wait()
        self.fevent.clear()
        # return

    def unlock(self):
        self.fevent.set()
开发者ID:thomasfire,项目名称:agent_smith,代码行数:35,代码来源:multiio.py

示例5: wait_for

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
    def wait_for(self, key, value):
        d = Manager().dict()
        d[key] = None
        v = Manager().Value('s', ' ')
        e = Event()

        p_state = Process(target=self.state_refresher, args=(self, d, e))
        p_input = Process(target=self.input_waiter, args=(self, v, e))
        p_state.start()
        p_input.start()

        while v.value != 'exit' and dict(d.items())[key] != value:
            e.wait()
            e.clear()

        self.state = d['state']
        self.current = d['current']
        self.enemy = d['enemy']
        self.battlefield = d['battlefield']

        p_state.terminate()
        p_input.terminate()
        curses.endwin()
        p_state.join()
        p_input.join()

        return True if dict(d.items())[key] == value else False
开发者ID:Scanters,项目名称:pyttleship,代码行数:29,代码来源:pyttleship.py

示例6: BroadcastServer

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class BroadcastServer(Process):
    def __init__(self, ip, port, message, name="BroadcastServer"):
        Process.__init__(self, name=name)
        self.logger = multiprocessing.get_logger()
        self.event = Event()
        self.message = message
        self.ip = ip
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(("", 0))

    def run(self):
        self.event.set()
        self.logger.debug("PID: %d" % multiprocessing.current_process().pid)
        while self.event.is_set():
            self.logger.debug("Sending: %s" % self.message)
            self.sock.sendto(self.message, (self.ip, self.port))
            time.sleep(1)

    def stop(self):
        self.logger.debug("Server will halt.")
        self.event.clear()
        self.terminate()
开发者ID:jg19,项目名称:playground,代码行数:27,代码来源:__init__.py

示例7: __init__

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class QueueTask:
    def __init__(self):
        self.queue = JoinableQueue()
        self.event = Event()
        atexit.register( self.queue.join )

        process = Process(target=self.work)
        process.daemon = True
        process.start()


    def work(self):
        while True:
            func, args, wait_for = self.queue.get()

            for evt in wait_for: 
                evt.wait()
            func(*args)
            self.event.set()

            self.queue.task_done()


    def enqueue(self, func, args=[], wait_for=[]):
        self.event.clear()
        self.queue.put( (func, args, wait_for) )

        return self.event 
开发者ID:wbkifun,项目名称:fdtd_accelerate,代码行数:30,代码来源:queue_multiprocessing_test.py

示例8: ClassifierWorkerPool

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class ClassifierWorkerPool(object):
    def __init__(self):
        self.queue = Queue(100)
        self.workers = []
        self.stop = Event()
        self.stop.clear()
        self.queue_feeder = QueueFeeder(self.queue, self.stop)

        row = TrainedClassifiers.objects(name=config.classifier).first()

        if not row:
            raise Exception("Classifier %s does not exists" % config.classifier)

        self.trained_classifier = row.get_classifier()

    def start(self):
        self.queue_feeder.start()

        for i in range(0, config.classifier_pool_size):
            worker = ClassifierWorker(self.trained_classifier, self.queue, self.stop)
            worker.start()
            self.workers.append(worker)

    def terminate(self):
        self.stop.set()
        self.queue_feeder.join()
        for w in self.workers:
            w.join()
开发者ID:BastinRobin,项目名称:streamcrab,代码行数:30,代码来源:pool.py

示例9: CaptureProcess

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class CaptureProcess(Process):
    """A process that fills a queue with images as captured from 
    a camera feed"""
    def __init__(self, capture, imageQueue):
        Process.__init__(self, name="Capture")
        self.imageQueue = imageQueue
        self.capture = capture
        self.keepGoing = Event()
        self.keepGoing.set()
        self.daemon = True

    def run(self):
        print "CaptureProcess pid: %s" % (self.pid,)
        while self.keepGoing.is_set():
            image = captureImage(self.capture)
#            sys.stdout.write(".")
            try:
                self.imageQueue.put(serializeImage(image), block=True, timeout=0.25)
            except FullException:
                try:
                    _ = self.imageQueue.get_nowait()
                except:
                    pass  # Try to clear the queue, but don't worry if someone snatches it first
    def stop(self):
        self.keepGoing.clear()
开发者ID:jbrowne,项目名称:UCSBsketch,代码行数:27,代码来源:ContinuousCapture.py

示例10: SetupBricks

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
def SetupBricks():
        allsuccess = False
        allprocs = []
        startvols = False

        events = {}
        ev = None
        for brick in BRICKS_IPADDRS: 
                ev = Event ()
                ev.clear()
                events[brick] = ev

        for brick in BRICKS_IPADDRS: 
                mychan,brickchan = Pipe()
                startvols = False
                if brick == NFSSERVER_ADDR:
                        startvols = True
                proc = Process (target=SetupBrick, args=(brick, brickchan, startvols, events,))
                allprocs.append ((proc, mychan, brickchan))

        if FUSE and NFSCLIENT_ADDR not in BRICKS_IPADDRS:
                ev = Event ()
                ev.clear()
                events[NFSCLIENT_ADDR] = ev
                mychan,brickchan = Pipe()
                startvols = False
                proc = Process (target=SetupBrick, args=(NFSCLIENT_ADDR, brickchan, startvols, events,))
                allprocs.append ((proc, mychan, brickchan))

        allsuccess = RunProcMonitorLoop(allprocs)
        return allsuccess
开发者ID:anushshetty,项目名称:glustersanity,代码行数:33,代码来源:testcontroller.py

示例11: face_proc

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
    def face_proc(self, child_face_recog: Pipe, e_new_person: Event):
        """
        Parallel process of saving people for face recognition

        Arguments:
            child_face_recog {Pipe} -- pipe for communication with parent process,
                recieve ROI ndarray type of recognized object
        """
        if not os.path.exists('humans'):
            print('created', os.getcwd())
            os.mkdir('humans')
        else:
            print('exist')
        os.chdir(os.path.join(os.getcwd(), 'humans'))
        is_first = True
        counter = 0
        while True:
            if e_new_person.is_set():
                counter = 0
                if not is_first:
                    os.chdir('..')
                new_dir = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
                os.mkdir(new_dir)
                print('Created', os.getcwd() + new_dir)
                os.chdir(os.path.join(os.getcwd(), new_dir))
                e_new_person.clear()
                is_first = False
            image = child_face_recog.recv()
            cv.imwrite(filename=str(counter) + '.jpg', img=image)
            print('image saved:', os.getcwd() + str(counter) + '.jpg')
            counter += 1
开发者ID:DiggiDon,项目名称:Tracking_system,代码行数:33,代码来源:track_system.py

示例12: ChildChecker

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class ChildChecker(threading.Thread):
    def __init__(self, killEvent):
        super(ChildChecker, self).__init__()
        self.killEvent = killEvent
        self.event = Event()
        self.process = Process(target=childsPlay, args=(self.event,))

    def run(self):
        self.process.start()

        while not self.killEvent.is_set():
            self.event.wait()
            print "Child checked, and is done playing"
            if raw_input("Do again? y/n:") == "y":
                self.event.clear()
                self.process = Process(target=endlessChildsPlay, args=(self.event,))
                self.process.start()
            else:
                self.cleanChild()
                self.killEvent.set()

    def join(self):
        print "Joining child process"
        # Timeout on 5 seconds
        self.process.join(5)

        if self.process.is_alive():
            print "Child did not join!  Killing.."
            self.process.terminate()
        print "Joining ChildChecker thread"
        super(ChildChecker, self).join()


    def cleanChild(self):
        print "Cleaning up the child..."
开发者ID:huangnauh,项目名称:learnpython,代码行数:37,代码来源:threadingfinished.py

示例13: MistProcess

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class MistProcess(Process):

    def __init__(self, gpio, sleep=1, name='MistProcess'):
        Process.__init__(self, name=name)
        self.logger = multiprocessing.get_logger()
        self.event = Event()
        self.name = name
        self.gpio = gpio
        self.sleep = sleep
        self.mist = mraa.Gpio(self.gpio)
        self.mist.dir(mraa.DIR_OUT)

    def _mist_on(self):
        self.logger.debug('Mist on')
        self.mist.write(1)

    def _mist_off(self):
        self.logger.debug('Mist off')
        if self.mist:
            self.mist.write(0)

    def run(self):
        self.event.set()
        self.logger.debug('PID: %d' % multiprocessing.current_process().pid)

        while self.event.is_set():
            self._mist_on()
            time.sleep(self.sleep)

    def stop(self):
        self.logger.debug('Process {} will halt.'.format(self.name))
        self.event.clear()
        self._mist_off()
开发者ID:GaragemHacker,项目名称:curytybainbox,代码行数:35,代码来源:mist.py

示例14: __init__

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class fmanager:
    def __init__(self,data,fn):
        self.sf = Event()
        self.sf.clear()

        self.nproc=cpu_count()
        self.pipes = [Pipe() for i in xrange(self.nproc)]
        self.e = [evaluator(self.pipes[i][1],self.sf,data,fn) for i in xrange(self.nproc)]
        null = [i.start() for i in self.e]
        return

    def __del__(self):
        self.sf.set()
        null = [i.join() for i in self.e]
        null = [i.terminate() for i in self.e]

        return

    def eval(self,x):
        nd = len(x)
        for i in xrange(nd):
            self.pipes[i % self.nproc][0].send([i, x[i]])
        solns = []
        while len(solns) < nd:
            for i in xrange(self.nproc):
                if self.pipes[i][0].poll(0.005):
                    solns.append(self.pipes[i][0].recv())
        solns.sort(key=lambda i: i[0])
        return [i[1] for i in solns]
开发者ID:markm541374,项目名称:pdirect,代码行数:31,代码来源:multitest.py

示例15: StoppableProcess

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import clear [as 别名]
class StoppableProcess(Process):
    """ Base class for Processes which require the ability
    to be stopped by a process-safe method call
    """

    def __init__(self):
        self._should_stop = Event()
        self._should_stop.clear()
        super(StoppableProcess, self).__init__()

    def join(self, timeout=0):
        """ Joins the current process and forces it to stop after
        the timeout if necessary

        :param timeout: Timeout duration in seconds
        """
        self._should_stop.wait(timeout)
        if not self.should_stop():
            self.stop()
        super(StoppableProcess, self).join(0)

    def stop(self):
        self._should_stop.set()

    def should_stop(self):
        return self._should_stop.is_set()

    def __repr__(self):
        return "<%s(should_stop=%s)>" % (
            self.__class__.__name__, self.should_stop())
开发者ID:ddale,项目名称:pymeasure,代码行数:32,代码来源:process.py


注:本文中的multiprocessing.Event.clear方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。