Python threading.Event() Examples

The following are 30 code examples for showing how to use threading.Event(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module threading , or try the search function .

Example 1
Project: clikit   Author: sdispater   File: progress_indicator.py    License: MIT License 6 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 2
Project: RF-Monitor   Author: EarToEarOak   File: gps.py    License: GNU General Public License v2.0 6 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 3
Project: RF-Monitor   Author: EarToEarOak   File: gps.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __read(self):
        for resp in self.__serial_read():
            nmea = resp.split('*')
            if len(nmea) == 2:
                data = nmea[0].split(',')
                if data[0] in ['GPGGA', 'GPGSV']:
                    checksum = self.__checksum(nmea[0])
                    if checksum == nmea[1]:
                        if data[0] == 'GPGGA':
                            self.__global_fix(data)
                        elif data[0] == 'GPGSV':
                            self.__sats(data)
                    else:
                        warn = 'Invalid checksum for {} sentence'.format(data[0])
                        event = Event(Events.GPS_WARN, msg=warn)
                        post_event(self._eventHandler, event) 
Example 4
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 5
Project: smbprotocol   Author: jborean93   File: change_notify.py    License: 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 6
Project: sanic   Author: huge-success   File: test_create_task.py    License: 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 7
Project: hyper-h2   Author: python-hyper   File: wsgi-server.py    License: 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 8
Project: dataflow   Author: tensorpack   File: parallel_map.py    License: 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 9
Project: kivy-smoothie-host   Author: wolfmanjm   File: comms.py    License: 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 10
Project: PythonClassBook   Author: PythonClassRoom   File: fig20_06.py    License: GNU General Public License v3.0 6 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 11
Project: misp42splunk   Author: remg427   File: engine.py    License: 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 12
Project: misp42splunk   Author: remg427   File: engine.py    License: 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 13
Project: tornado-zh   Author: tao12345666333   File: ioloop_test.py    License: 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 14
Project: tornado-zh   Author: tao12345666333   File: ioloop_test.py    License: 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 15
Project: BASS   Author: Cisco-Talos   File: core.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, job_id):
        self.samples = []
        self.status = self.STATUS_CREATED
        self.thread = None
        self.finished = Event()
        self.status_lock = Lock()
        self.id = job_id 
Example 16
Project: RF-Monitor   Author: EarToEarOak   File: gps.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __timeout(self):
        self.stop()
        event = Event(Events.GPS_TIMEOUT, msg='GPS timeout')
        post_event(self._eventHandler, event) 
Example 17
Project: RF-Monitor   Author: EarToEarOak   File: gps.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __global_fix(self, data):
        if data[6] in ['1', '2']:
            lat = self.__coord(data[2], data[3])
            lon = self.__coord(data[4], data[5])

            event = Event(Events.GPS_LOC, loc=(lat, lon))
            post_event(self._eventHandler, event) 
Example 18
Project: RF-Monitor   Author: EarToEarOak   File: gps.py    License: GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        try:
            self.__open()
            self.__read()
        except SerialException as error:
            event = Event(Events.GPS_ERROR, msg=error.message)
            post_event(self._eventHandler, event)
        except OSError as error:
            event = Event(Events.GPS_ERROR, msg=error)
            post_event(self._eventHandler, event)
        except ValueError as error:
            event = Event(Events.GPS_ERROR, msg=error)
            post_event(self._eventHandler, event)

        self.__close() 
Example 19
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: util.py    License: MIT License 5 votes vote down vote up
def __init__(self, protected_path, timeout=0.0, delay=0.05):
        """Create new :class:`LockFile` object."""
        self.lockfile = protected_path + '.lock'
        self._lockfile = None
        self.timeout = timeout
        self.delay = delay
        self._lock = Event()
        atexit.register(self.release) 
Example 20
Project: cherrypy   Author: cherrypy   File: caching.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __setitem__(self, key, value):
        """Set the cached value for the given key."""
        existing = self.get(key)
        dict.__setitem__(self, key, value)
        if isinstance(existing, threading.Event):
            # Set Event.result so other threads waiting on it have
            # immediate access without needing to poll the cache again.
            existing.result = value
            existing.set() 
Example 21
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: ImageAnim.py    License: MIT License 5 votes vote down vote up
def __init__(self, imganim):
        super().__init__()
        self.setDaemon(True)
        self._stop_event = threading.Event()
        self._wait_event = threading.Event()
        self.anim = imganim 
Example 22
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: kimotion.py    License: MIT License 5 votes vote down vote up
def thread_lock():
    e = threading.Event()
    e.lock = e.clear
    e.release = e.set
    e.is_released = e.is_set

    e.release()
    return e 
Example 23
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: kimotion.py    License: MIT License 5 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 24
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: events.py    License: MIT License 5 votes vote down vote up
def myThread(myEvent):
  while not myEvent.is_set():
    print("Waiting for Event to be set")
    time.sleep(1)
  print("myEvent has been set") 
Example 25
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: events.py    License: MIT License 5 votes vote down vote up
def main():
  myEvent = threading.Event()
  thread1 = threading.Thread(target=myThread, args=(myEvent,))
  thread1.start()

  time.sleep(10)
  myEvent.set() 
Example 26
Project: LPHK   Author: nimaid   File: scripts.py    License: GNU General Public License v3.0 5 votes vote down vote up
def schedule_script(script_in, x, y):
    global threads
    global to_run
    global running
    coords = "(" + str(x) + ", " + str(y) + ")"

    if threads[x][y] != None:
        if threads[x][y].is_alive():
            print("[scripts] " + coords + " Script already running, killing script....")
            threads[x][y].kill.set()
            return

    if (x, y) in [l[1:] for l in to_run]:
        print("[scripts] " + coords + " Script already scheduled, unscheduling...")
        indexes = [i for i, v in enumerate(to_run) if ((v[1] == x) and (v[2] == y))]
        for index in indexes[::-1]:
            temp = to_run.pop(index)
        return

    if script_in.split("\n")[0].split(" ")[0] in ASYNC_HEADERS:
        print("[scripts] " + coords + " Starting asynchronous script in background...")
        threads[x][y] = threading.Thread(target=run_script, args=(script_in,x,y))
        threads[x][y].kill = threading.Event()
        threads[x][y].start()
    elif not running:
        print("[scripts] " + coords + " No script running, starting script in background...")
        threads[x][y] = threading.Thread(target=run_script_and_run_next, args=(script_in,x,y))
        threads[x][y].kill = threading.Event()
        threads[x][y].start()
    else:
        print("[scripts] " + coords + " A script is already running, scheduling...")
        to_run.append((script_in, x, y))
    lp_colors.updateXY(x, y) 
Example 27
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: io.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, iters, rename_data=None, rename_label=None):
        super(PrefetchingIter, self).__init__()
        if not isinstance(iters, list):
            iters = [iters]
        self.n_iter = len(iters)
        assert self.n_iter > 0
        self.iters = iters
        self.rename_data = rename_data
        self.rename_label = rename_label
        self.batch_size = self.provide_data[0][1][0]
        self.data_ready = [threading.Event() for i in range(self.n_iter)]
        self.data_taken = [threading.Event() for i in range(self.n_iter)]
        for i in self.data_taken:
            i.set()
        self.started = True
        self.current_batch = [None for i in range(self.n_iter)]
        self.next_batch = [None for i in range(self.n_iter)]
        def prefetch_func(self, i):
            """Thread entry"""
            while True:
                self.data_taken[i].wait()
                if not self.started:
                    break
                try:
                    self.next_batch[i] = self.iters[i].next()
                except StopIteration:
                    self.next_batch[i] = None
                self.data_taken[i].clear()
                self.data_ready[i].set()
        self.prefetch_threads = [threading.Thread(target=prefetch_func, args=[self, i]) \
                                 for i in range(self.n_iter)]
        for thread in self.prefetch_threads:
            thread.setDaemon(True)
            thread.start() 
Example 28
def test_context():
    ctx_list = []
    ctx_list.append(Context.default_ctx)
    def f():
        set_default_context(mx.gpu(11))
        ctx_list.append(Context.default_ctx)
    thread = threading.Thread(target=f)
    thread.start()
    thread.join()
    assert Context.devtype2str[ctx_list[0].device_typeid] == "cpu"
    assert ctx_list[0].device_id == 0
    assert Context.devtype2str[ctx_list[1].device_typeid] == "gpu"
    assert ctx_list[1].device_id == 11

    event = threading.Event()
    status = [False]
    def g():
        with mx.cpu(10):
            event.wait()
            if Context.default_ctx.device_id == 10:
                status[0] = True
    thread = threading.Thread(target=g)
    thread.start()
    Context.default_ctx = Context("cpu", 11)
    event.set()
    thread.join()
    event.clear()
    assert status[0], "Spawned thread didn't set the correct context" 
Example 29
def test_attrscope():
    attrscope_list = []
    AttrScope.current = AttrScope(y="hi", z="hey")
    attrscope_list.append(AttrScope.current)
    def f():
        AttrScope.current = AttrScope(x="hello")
        attrscope_list.append(AttrScope.current)
    thread = threading.Thread(target=f)
    thread.start()
    thread.join()
    assert len(attrscope_list[0]._attr) == 2
    assert attrscope_list[1]._attr["x"] == "hello"

    event = threading.Event()
    status = [False]
    def g():
        with mx.AttrScope(x="hello"):
            event.wait()
            if "hello" in AttrScope.current._attr.values():
                status[0] = True
    thread = threading.Thread(target=g)
    thread.start()
    AttrScope.current = AttrScope(x="hi")
    event.set()
    thread.join()
    AttrScope.current = AttrScope()
    event.clear()
    assert status[0], "Spawned thread didn't set the correct attr key values" 
Example 30
def test_name():
    name_list = []
    NameManager.current = NameManager()
    NameManager.current.get(None, "main_thread")
    name_list.append(NameManager.current)
    def f():
        NameManager.current = NameManager()
        NameManager.current.get(None, "spawned_thread")
        name_list.append(NameManager.current)
    thread = threading.Thread(target=f)
    thread.start()
    thread.join()
    assert "main_thread" in name_list[0]._counter, "cannot find the string `main thread` in name_list[0]._counter"
    assert "spawned_thread" in name_list[1]._counter, "cannot find the string `spawned thread` in name_list[1]._counter"

    event = threading.Event()
    status = [False]
    def g():
        with NameManager():
            if "main_thread" not in NameManager.current._counter:
                status[0] = True
    thread = threading.Thread(target=g)
    thread.start()
    NameManager.current = NameManager()
    NameManager.current.get(None, "main_thread")
    event.set()
    thread.join()
    event.clear()
    assert status[0], "Spawned thread isn't using thread local NameManager"