Python threading.Event() Examples

The following are 30 code examples of threading.Event(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module threading , or try the search function .
Example #1
Source File: fig20_06.py    From PythonClassBook with GNU General Public License v3.0 8 votes vote down vote up
def __init__( self ):
      """Initialize variables and setup server"""
      
      HOST = ""
      PORT = 5000

      self.board = []
      self.currentPlayer = 0
      self.turnCondition = threading.Condition()
      self.gameBeginEvent = threading.Event()

      for i in range( 9 ):
         self.board.append( None )

      # setup server socket
      self.server = socket.socket( socket.AF_INET,
         socket.SOCK_STREAM )
      self.server.bind( ( HOST, PORT ) )
      self.display( "Server awaiting connections..." ) 
Example #2
Source File: progress_indicator.py    From clikit with MIT License 7 votes vote down vote up
def auto(self, start_message, end_message):
        """
        Auto progress.
        """
        self._auto_running = threading.Event()
        self._auto_thread = threading.Thread(target=self._spin)

        self.start(start_message)
        self._auto_thread.start()

        try:
            yield self
        except (Exception, KeyboardInterrupt):
            self._io.write_line("")

            self._auto_running.set()
            self._auto_thread.join()

            raise

        self.finish(end_message, reset_indicator=True) 
Example #3
Source File: gps.py    From RF-Monitor with GNU General Public License v2.0 7 votes vote down vote up
def __sats(self, data):
        message = int(data[1])
        messages = int(data[1])
        viewed = int(data[3])

        if message == 1:
            self._sats.clear()

        blocks = (len(data) - 4) / 4
        for i in range(0, blocks):
            sat = int(data[4 + i * 4])
            level = data[7 + i * 4]
            used = True
            if level == '':
                level = None
                used = False
            else:
                level = int(level)
            self._sats[sat] = {'Level': level,
                               'Used': used}

        if message == messages and len(self._sats) == viewed:
            event = Event(Events.GPS_SATS, sats=self._sats)
            post_event(self._eventHandler, event) 
Example #4
Source File: wsgi-server.py    From hyper-h2 with MIT License 6 votes vote down vote up
def send_response(self, stream_id, headers):
        """
        Thread-safe method called from outside the main asyncio thread in order
        to send the HTTP response headers on behalf of a WSGI application.

        Returns a threading event that will fire when the headers have been
        emitted to the network.
        """
        event = threading.Event()

        def _inner_send(stream_id, headers, event):
            self.conn.send_headers(stream_id, headers, end_stream=False)
            self.transport.write(self.conn.data_to_send())
            event.set()

        self._loop.call_soon_threadsafe(
            _inner_send,
            stream_id,
            headers,
            event
        )
        return event 
Example #5
Source File: test_create_task.py    From sanic with MIT License 6 votes vote down vote up
def test_create_task(app):
    e = Event()

    async def coro():
        await asyncio.sleep(0.05)
        e.set()

    app.add_task(coro)

    @app.route("/early")
    def not_set(request):
        return text(str(e.is_set()))

    @app.route("/late")
    async def set(request):
        await asyncio.sleep(0.1)
        return text(str(e.is_set()))

    request, response = app.test_client.get("/early")
    assert response.body == b"False"

    request, response = app.test_client.get("/late")
    assert response.body == b"True" 
Example #6
Source File: test_thread_local.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_blockscope():
    class dummy_block(object):
        def __init__(self, prefix):
            self.prefix = prefix
            self._empty_prefix = False
    blockscope_list = []
    status = [False]
    event = threading.Event()
    def f():
        with block._BlockScope(dummy_block("spawned_")):
            x= NameManager.current.get(None, "hello")
            event.wait()
            if x == "spawned_hello0":
                status[0] = True
    thread = threading.Thread(target=f)
    thread.start()
    block._BlockScope.create("main_thread", None, "hi")
    event.set()
    thread.join()
    event.clear()
    assert status[0], "Spawned thread isn't using the correct blockscope namemanager" 
Example #7
Source File: ioloop_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_add_callback_while_closing(self):
        # Issue #635: add_callback() should raise a clean exception
        # if called while another thread is closing the IOLoop.
        closing = threading.Event()

        def target():
            other_ioloop.add_callback(other_ioloop.stop)
            other_ioloop.start()
            closing.set()
            other_ioloop.close(all_fds=True)
        other_ioloop = IOLoop()
        thread = threading.Thread(target=target)
        thread.start()
        closing.wait()
        for i in range(1000):
            try:
                other_ioloop.add_callback(lambda: None)
            except RuntimeError as e:
                self.assertEqual("IOLoop is closing", str(e))
                break 
Example #8
Source File: engine.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, request, context, checkpoint_mgr, proxy=None):
        """
        Constructs a `Job` with properties request, context and a
         optional proxy setting.
        :param request: A `Request` instance which contains request settings.
        :param context: A values set contains initial values for template
         variables.
        :param proxy: A optional `Proxy` object contains proxy related
         settings.
        """
        self._request = request
        self._context = context
        self._checkpoint_mgr = checkpoint_mgr
        self._client = HttpClient(proxy)
        self._stopped = True
        self._should_stop = False

        self._request_iterated_count = 0
        self._iteration_mode = self._request.iteration_mode
        self._max_iteration_count = self._get_max_iteration_count()

        self._running_thread = None
        self._terminated = threading.Event() 
Example #9
Source File: ioloop_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_add_callback_while_closing(self):
        # Issue #635: add_callback() should raise a clean exception
        # if called while another thread is closing the IOLoop.
        closing = threading.Event()

        def target():
            other_ioloop.add_callback(other_ioloop.stop)
            other_ioloop.start()
            closing.set()
            other_ioloop.close(all_fds=True)
        other_ioloop = IOLoop()
        thread = threading.Thread(target=target)
        thread.start()
        closing.wait()
        for i in range(1000):
            try:
                other_ioloop.add_callback(lambda: None)
            except RuntimeError as e:
                self.assertEqual("IOLoop is closing", str(e))
                break 
Example #10
Source File: comms.py    From kivy-smoothie-host with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, app, reportrate=1):
        self.app = app
        self.proto = None
        self.timer = None
        self._fragment = None
        self.abort_stream = False
        self.pause_stream = False  # asyncio.Event()
        self.okcnt = None
        self.ping_pong = True  # ping pong protocol for streaming
        self.file_streamer = None
        self.report_rate = reportrate
        self._reroute_incoming_data_to = None
        self._restart_timer = False
        self.is_streaming = False
        self.do_query = False
        self.last_tool = None
        self.is_suspend = False
        self.m0 = None
        self.net_connection = False
        self.log = logging.getLogger()  # .getChild('Comms')
        # logging.getLogger().setLevel(logging.DEBUG) 
Example #11
Source File: kimotion.py    From BiblioPixelAnimations with MIT License 6 votes vote down vote up
def __init__(self, server):
        super().__init__()
        self.setDaemon(True)
        self._stop = threading.Event()
        self._reading = thread_lock()
        self.dt = np.dtype(np.uint16)
        self.dt = self.dt.newbyteorder('<')
        self._data = [np.zeros(WS_FRAME_SIZE, self.dt),
                      np.zeros(WS_FRAME_SIZE, self.dt)]
        self._buf = False
        self.ws = create_connection("ws://{}/".format(server)) 
Example #12
Source File: change_notify.py    From smbprotocol with MIT License 6 votes vote down vote up
def __init__(self, open):
        """
        A class that encapsulates a FileSystemWatcher over SMB. It is designed to make it easy to run the watcher in
        the background and provide an event that is fired when the server notifies that a change has occurred. It is
        up to the caller to action on that event through their own sync or asynchronous implementation.

        :param open: The Open() class of a directory to watch for change notifications.
        """
        self.open = open
        self.response_event = threading.Event()

        self._t_on_response = threading.Thread(target=self._on_response)
        self._t_on_response.daemon = True
        self._t_exc = None
        self._request = None
        self._file_actions = None
        self._result_lock = threading.Lock()  # Used to ensure the result is only processed once 
Example #13
Source File: parallel_map.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def reset_state(self):
        super(MultiThreadMapData, self).reset_state()
        if self._threads:
            self._threads[0].stop()
            for t in self._threads:
                t.join()

        self._in_queue = queue.Queue()
        self._out_queue = queue.Queue()
        self._evt = threading.Event()
        self._threads = [MultiThreadMapData._Worker(
            self._in_queue, self._out_queue, self._evt, self.map_func)
            for _ in range(self.num_thread)]
        for t in self._threads:
            t.start()

        self._guard = DataFlowReentrantGuard()

        # Call once at the beginning, to ensure inq+outq has a total of buffer_size elements
        self._fill_buffer() 
Example #14
Source File: engine.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, request, context, checkpoint_mgr, proxy=None):
        """
        Constructs a `Job` with properties request, context and a
         optional proxy setting.
        :param request: A `Request` instance which contains request settings.
        :param context: A values set contains initial values for template
         variables.
        :param proxy: A optional `Proxy` object contains proxy related
         settings.
        """
        self._request = request
        self._context = context
        self._checkpoint_mgr = checkpoint_mgr
        self._client = HttpClient(proxy)
        self._stopped = True
        self._should_stop = False

        self._request_iterated_count = 0
        self._iteration_mode = self._request.iteration_mode
        self._max_iteration_count = self._get_max_iteration_count()

        self._running_thread = None
        self._terminated = threading.Event() 
Example #15
Source File: comms-net.py    From kivy-smoothie-host with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, app, reports=True):
        self.app = app
        self.proto = None
        self.timer= None
        self._fragment= None
        self.reports= reports
        self.abort_stream= False
        self.pause_stream= False #asyncio.Event()
        self.okcnt= None
        self.ping_pong= False # ping pong protocol for streaming
        self.file_streamer= None

        self.log = logging.getLogger() #.getChild('CommsNet')
        #logging.getLogger().setLevel(logging.DEBUG) 
Example #16
Source File: comms.py    From kivy-smoothie-host with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
            super(CommsApp, self).__init__()
            self.root = self
            self.log = logging.getLogger()
            self.start_event = threading.Event()
            self.end_event = threading.Event()
            self.is_connected = False
            self.ok = False
            self.main_window = self
            self.timer = None
            self.is_cnc = True
            self.fast_stream = False 
Example #17
Source File: comms-net.py    From kivy-smoothie-host with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, cb):
        super().__init__()
        self.cb = cb
        self.cnt= 0
        self.log = logging.getLogger() #.getChild('TcpConnection')
        self.log.info('TcpConnection: creating TcpCOnnection')
        self.queue = asyncio.Queue(maxsize=100)
        self.hipri_queue = asyncio.Queue()
        self._ready = asyncio.Event()
        self._msg_ready = asyncio.Semaphore(value=0)
        self.tsk= asyncio.async(self._send_messages())  # Or asyncio.ensure_future if using 3.4.3+
        self.flush= False 
Example #18
Source File: _base.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.event = threading.Event()
        self.finished_futures = [] 
Example #19
Source File: base_camera.py    From object-detection with MIT License 5 votes vote down vote up
def wait(self):
        """Invoked from each client's thread to wait for the next frame."""
        ident = get_ident()
        if ident not in self.events:
            # this is a new client
            # add an entry for it in the self.events dict
            # each entry has two elements, a threading.Event() and a timestamp
            self.events[ident] = [threading.Event(), time.time()]
        return self.events[ident][0].wait() 
Example #20
Source File: ioloop_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_add_future_stack_context(self):
        ready = threading.Event()

        def task():
            # we must wait for the ioloop callback to be scheduled before
            # the task completes to ensure that add_future adds the callback
            # asynchronously (which is the scenario in which capturing
            # the stack_context matters)
            ready.wait(1)
            assert ready.isSet(), "timed out"
            raise Exception("worker")

        def callback(future):
            self.future = future
            raise Exception("callback")

        def handle_exception(typ, value, traceback):
            self.exception = value
            self.stop()
            return True

        # stack_context propagates to the ioloop callback, but the worker
        # task just has its exceptions caught and saved in the Future.
        with futures.ThreadPoolExecutor(1) as pool:
            with ExceptionStackContext(handle_exception):
                self.io_loop.add_future(pool.submit(task), callback)
            ready.set()
        self.wait()

        self.assertEqual(self.exception.args[0], "callback")
        self.assertEqual(self.future.exception().args[0], "worker") 
Example #21
Source File: ioloop_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_add_future_stack_context(self):
        ready = threading.Event()

        def task():
            # we must wait for the ioloop callback to be scheduled before
            # the task completes to ensure that add_future adds the callback
            # asynchronously (which is the scenario in which capturing
            # the stack_context matters)
            ready.wait(1)
            assert ready.isSet(), "timed out"
            raise Exception("worker")

        def callback(future):
            self.future = future
            raise Exception("callback")

        def handle_exception(typ, value, traceback):
            self.exception = value
            self.stop()
            return True

        # stack_context propagates to the ioloop callback, but the worker
        # task just has its exceptions caught and saved in the Future.
        with futures.ThreadPoolExecutor(1) as pool:
            with ExceptionStackContext(handle_exception):
                self.io_loop.add_future(pool.submit(task), callback)
            ready.set()
        self.wait()

        self.assertEqual(self.exception.args[0], "callback")
        self.assertEqual(self.future.exception().args[0], "worker") 
Example #22
Source File: metricd.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def __init__(self, worker_id, conf, interval_delay=0):
        super(MetricProcessBase, self).__init__(worker_id)
        self.conf = conf
        self.startup_delay = self.worker_id = worker_id
        self.interval_delay = interval_delay
        self._wake_up = threading.Event()
        self._shutdown = threading.Event()
        self._shutdown_done = threading.Event() 
Example #23
Source File: oracle.py    From pwnypack with MIT License 5 votes vote down vote up
def encrypt_block(oracle, block_len, block, plain, pool):
    if pool is not None:
        event_factory = multiprocessing.Manager().Event
        map_func = pool.imap_unordered
    else:
        event_factory = threading.Event
        map_func = map

    cipher = bytearray([0] * block_len)

    for i in range(block_len - 1, -1, -1):
        chunk = cipher[:]

        for k in range(i + 1, block_len):
            chunk[k] ^= block_len - i

        event = event_factory()
        f = functools.partial(check_padding_encrypt, event, oracle, block_len, chunk, block, i)

        for result in map_func(f, interruptable_iter(event, range(256))):
            if result is not None:
                cipher[i] = result[i] ^ (block_len - i)

        if not event.is_set():
            raise RuntimeError('Oracle is unstable')

    for k, p in enumerate(plain):
        cipher[k] ^= p

    return cipher 
Example #24
Source File: concurrency.py    From dataflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, evt=None):
        """
        Args:
            evt(threading.Event): if None, will create one.
        """
        super(StoppableThread, self).__init__()
        if evt is None:
            evt = threading.Event()
        self._stop_evt = evt 
Example #25
Source File: ListenerThread.py    From OpenTrader with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, sChartId, **dArgs):

        self.oLocal = threading.local()
        self._running = threading.Event()

        self.lCharts = []
        self.jLastRetval = []
        self.jLastTick = []
        self.jLastBar = []
        self.gLastTimer = []
        self.dRetvals = {}
        self.bPprint = False
        self.lHide = [] 
Example #26
Source File: polling.py    From qtsass with MIT License 5 votes vote down vote up
def __init__(self, callback, interval):
        """Initialize the thread.

        :param callback: Callback function to repeat.
        :param interval: Number of seconds to sleep between calls.
        """
        super(PollingThread, self).__init__()
        self.daemon = True
        self.callback = callback
        self.interval = interval
        self._shutdown = threading.Event()
        self._stopped = threading.Event()
        self._started = threading.Event()
        atexit.register(self.stop) 
Example #27
Source File: pool.py    From jawfish with MIT License 5 votes vote down vote up
def __init__(self, cache, callback, error_callback):
        self._event = threading.Event()
        self._job = next(job_counter)
        self._cache = cache
        self._callback = callback
        self._error_callback = error_callback
        cache[self._job] = self 
Example #28
Source File: handlers.py    From jawfish with MIT License 5 votes vote down vote up
def __init__(self, queue, *handlers):
            """
            Initialise an instance with the specified queue and
            handlers.
            """
            self.queue = queue
            self.handlers = handlers
            self._stop = threading.Event()
            self._thread = None 
Example #29
Source File: handlers.py    From jawfish with MIT License 5 votes vote down vote up
def close(self):
        """
        Clean up this handler.

        You can remove the application name from the registry as a
        source of event log entries. However, if you do this, you will
        not be able to see the events as you intended in the Event Log
        Viewer - it needs to be able to access the registry to get the
        DLL name.
        """
        #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
        logging.Handler.close(self) 
Example #30
Source File: wsgi-server.py    From hyper-h2 with MIT License 5 votes vote down vote up
def data_for_stream(self, stream_id, data):
        """
        Thread-safe method called from outside the main asyncio thread in order
        to send data on behalf of a WSGI application.

        Places data being written by a stream on an asyncio queue. Returns a
        threading event that will fire when that data is sent.
        """
        event = threading.Event()
        self._loop.call_soon_threadsafe(
            self._stream_data.put_nowait,
            (stream_id, data, event)
        )
        return event