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


Python Event.wait方法代码示例

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


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

示例1: wait_for

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [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

示例2: execute_action

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
    def execute_action(self, action):
        event = Event()
        queue = Queue()
        proc = Process(
            target=execute_action_proc,
            args=(self.execute, action, event, queue))
        proc.start()

        # Send heartbeat.
        heartbeat_retry = 0
        while not event.is_set():
            event.wait(config.ACTIVITY_HEARTBEAT_INTERVAL)
            try:
                res = self.heartbeat(self.task_token)
                if res['cancelRequested']:
                    proc.terminate()
                    proc.join()
                    return Result('cancelled', -1, '', '', '', -1)
            except Exception as err:
                if heartbeat_retry <= config.ACTIVITY_HEARTBEAT_MAX_RETRY:
                    heartbeat_retry += 1
                    continue
                else:
                    proc.terminate()
                    proc.join()
                    raise

        # Evaluate the result.
        result = queue.get_nowait()
        proc.join()
        return result
开发者ID:badboy99tw,项目名称:mass,代码行数:33,代码来源:__init__.py

示例3: test_server_client

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
    def test_server_client(self):
        import time

        send_msg = u'test ฟนำีฟนำีฟนำีฟนำี'
        server_start = Event()

        def on_message(msg):
            self.assertEqual(msg, send_msg)
            return msg

        def server():
            PostofficeServer(ip='0.0.0.0', port=4000, on_message=on_message, after_start_cb=lambda: server_start.set())

        def client():
            client = PostofficeClient(ip='localhost', port=4000)
            response = client.send(send_msg)
            self.assertEqual(response, send_msg)

        from multiprocessing import Process
        p = Process(target=server)
        try:
            p.start()
            server_start.wait()
            client()
            p.terminate()
            p.join()
        except Exception as e:
            # gracefully stop
            p.terminate()
            p.join()
            raise
开发者ID:phizaz,项目名称:gaw,代码行数:33,代码来源:test_postoffice.py

示例4: test_multiple_concurrent_request_on_same_client

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
    def test_multiple_concurrent_request_on_same_client(self):
        import time
        from multiprocessing.pool import ThreadPool

        send_msg = u'test ฟนำีฟนำีฟนำีฟนำี'
        server_start = Event()

        def on_message(msg):
            self.assertEqual(msg, send_msg)

        def server():
            PostofficeServer(ip='0.0.0.0', port=4000, on_message=on_message, after_start_cb=lambda: server_start.set())

        from multiprocessing import Process
        p = Process(target=server)
        try:
            p.start()

            server_start.wait()

            c = PostofficeClient(ip='localhost', port=4000)

            def client(ith):
                c.send(send_msg)

            pool = ThreadPool(100)
            pool.map(client, [i for i in range(1000)])

            p.terminate()
            p.join()
        except Exception as e:
            # gracefully stop
            p.terminate()
            p.join()
            raise
开发者ID:phizaz,项目名称:gaw,代码行数:37,代码来源:test_postoffice.py

示例5: ServerProc

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
class ServerProc(object):
    def __init__(self):
        self.proc = None
        self.daemon = None
        self.stop = Event()

    def start(self, init_func, config, paths, port):
        self.proc = Process(target=self.create_daemon, args=(init_func, config, paths, port))
        self.proc.daemon = True
        self.proc.start()

    def create_daemon(self, init_func, config, paths, port):
        try:
            self.daemon = init_func(config, paths, port)
        except socket.error:
            logger.error("Socket error on port %s" % port)
            raise

        if self.daemon:
            self.daemon.start(block=False)
            try:
                self.stop.wait()
            except KeyboardInterrupt:
                pass

    def wait(self):
        self.stop.set()
        self.proc.join()

    def kill(self):
        self.stop.set()
        self.proc.terminate()
        self.proc.join()
开发者ID:Acidburn0zzz,项目名称:web-platform-tests,代码行数:35,代码来源:serve.py

示例6: test_host_is_down

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
    def test_host_is_down(self):
        from multiprocessing import Event, Process

        server_start = Event()

        def a(path):
            return path

        def b(path, a, b):
            return a + b

        def c(path, a, b):
            return a * b

        def server():
            server = JsonSocketServer(ip='0.0.0.0', port=4000, verbose=True)
            server.register_route(u'a ฟนำี', a)
            server.register_route('b', b)
            server.register_route('c', c)
            server.start(lambda: server_start.set())

        def client():
            client = JsonSocketClient(verbose=True)
            self.assertRaises(Exception, client.request, ip='localhost', port=4000, path=u'a ฟนำี', payload=dict(), retries=0)

        p = Process(target=server)
        p.start()

        server_start.wait()

        p.terminate()
        p.join()

        client()
开发者ID:phizaz,项目名称:gaw,代码行数:36,代码来源:test_jsonsocketserver.py

示例7: StoppableProcess

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
class StoppableProcess(Process):
    exit = None
    sleep = None

    def __init__(self, sleep=1, *args, **kwargs):
        self.exit = Event()
        self.sleep = sleep
        super(StoppableProcess, self).__init__(*args, **kwargs)

    def _setup(self):
        pass

    def _teardown(self):
        pass

    def _ping(self):
        raise NotImplementedError

    def _should_exit(self):
        return self.exit.wait(0)

    def run(self):
        self._setup()
        while True:
            if self._ping() or self.exit.wait(self.sleep * 1.0):
                self._teardown()
                return

    def stop(self):
        self.exit.set()
        self.join(self.sleep)
        if self.is_alive():
            self.terminate()
开发者ID:c17r,项目名称:tic-tweet-toe,代码行数:35,代码来源:stoppable_process.py

示例8: test_host_is_down

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
    def test_host_is_down(self):
        from gaw import interface_class, service_class, client_class

        server_start = Event()

        @interface_class(service_name='ServiceInterfaceStyle')
        class Interface(object):
            def ping(self): pass

        def server():
            @service_class
            class Service(Interface):
                def ping(self): return True

            GawServer(ip='0.0.0.0', port=4000).add(Service).run(lambda: server_start.set())

        def client():
            @client_class(ip='localhost', port=4000, retries=0)  # do not retry
            class Client(Interface): pass

            self.assertRaises(Exception, Client().ping)

        p = Process(target=server)
        p.start()

        server_start.wait()
        p.terminate()
        p.join()

        client()
开发者ID:phizaz,项目名称:gaw,代码行数:32,代码来源:test_gaw.py

示例9: pipelineDaemon

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
def pipelineDaemon(pipeline, returnEvent, options=None, programName=None):
    """Launches Pyro server and (if specified by options) pipeline executors"""
    
    #check for valid pipeline 
    if pipeline.runnable.empty()==None:
        print "Pipeline has no runnable stages. Exiting..."
        sys.exit()

    if options.urifile==None:
        options.urifile = os.path.abspath(os.curdir + "/" + "uri")
    
    e = Event()
    process = Process(target=launchServer, args=(pipeline,options,e,))
    process.start()
    e.wait()
    if options.num_exec != 0:
        processes = [Process(target=launchPipelineExecutor, args=(options,programName,)) for i in range(options.num_exec)]
        for p in processes:
            p.start()
        for p in processes:
            p.join()
    
    #Return to calling code if pipeline has no more runnable stages:
    #Event will be cleared once clients are unregistered. 
    while e.is_set():
        time.sleep(5)
    returnEvent.set()
开发者ID:frasermac,项目名称:pydpiper,代码行数:29,代码来源:pipeline.py

示例10: StoppableProcess

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [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

示例11: TestProxyData

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [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

示例12: SharedFile

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [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

示例13: ChildChecker

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [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

示例14: test_play_and_record

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
    def test_play_and_record(self):
        """
        Verifies that a Device and play back prerecorded events.
        """
        device = evemu.Device(self.get_device_file())
        devnode = device.devnode
        events_file = self.get_events_file()
        # device.record() calls evemu_record() and is thus missing the
        # description that the input file has
        with open(events_file) as e:
            indata = extract_events(strip_comments(e.readlines()))

        recording_started = Event()
        q = Queue()
        record_process = Process(target=record,
                                 args=(recording_started, devnode, q))
        record_process.start()
        recording_started.wait(100)
        device.play(open(events_file))

        outdata = strip_comments(q.get())
        record_process.join()

        self.assertEquals(len(indata), len(outdata))
        fuzz = re.compile("E: \d+\.\d+ (.*)")
        for i in range(len(indata)):
            lhs = fuzz.match(indata[i])
            self.assertTrue(lhs)
            rhs = fuzz.match(outdata[i])
            self.assertTrue(rhs)
            self.assertEquals(lhs.group(1), rhs.group(1))
开发者ID:bentiss,项目名称:evemu,代码行数:33,代码来源:test_device.py

示例15: throughput

# 需要导入模块: from multiprocessing import Event [as 别名]
# 或者: from multiprocessing.Event import wait [as 别名]
def throughput(seconds=10,cocurrency=1):
    '''
    seconds should be greater than or equal to 10
    1000w pv = 115 rps
    '''
    stop_flag=Event()
    processes=[]
    t=Timer(seconds,stop,args=[stop_flag])
    q = Queue()
    for i in range(cocurrency):
        processes.append(Process(target=run,args=(q,stop_flag)))
    t.start()
    for p in processes:
        p.start()
    #print 'start waiting for workers:',len(processes)
    stop_flag.wait()
    for t in processes:
        t.join()
    total=err=cost=0
    while not q.empty():
        (req_counter,err_counter,time_cost)=q.get()
        total=total+req_counter
        err=err+err_counter
        cost=cost+time_cost
    cost=cost/total if total>0 else 0

    return total,err,cost
开发者ID:fengclient,项目名称:myalogrithms,代码行数:29,代码来源:benchmark.py


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