Python threading.ThreadError() Examples

The following are 30 code examples of threading.ThreadError(). 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: threading.py    From ipygee with MIT License 6 votes vote down vote up
def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        raise AssertionError("could not determine the thread's id") 
Example #2
Source File: process_lock.py    From fasteners with Apache License 2.0 6 votes vote down vote up
def _try_acquire(self, blocking, watch):
        try:
            self.trylock()
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                if not blocking or watch.expired():
                    return False
                else:
                    raise _utils.RetryAgain()
            else:
                raise threading.ThreadError("Unable to acquire lock on"
                                            " `%(path)s` due to"
                                            " %(exception)s" %
                                            {
                                                'path': self.path,
                                                'exception': e,
                                            })
        else:
            return True 
Example #3
Source File: process_lock.py    From fasteners with Apache License 2.0 6 votes vote down vote up
def release(self):
        """Release the previously acquired lock."""
        if not self.acquired:
            raise threading.ThreadError("Unable to release an unacquired"
                                        " lock")
        try:
            self.unlock()
        except IOError:
            self.logger.exception("Could not unlock the acquired lock opened"
                                  " on `%s`", self.path)
        else:
            self.acquired = False
            try:
                self._do_close()
            except IOError:
                self.logger.exception("Could not close the file handle"
                                      " opened on `%s`", self.path)
            else:
                self.logger.log(_utils.BLATHER,
                                "Unlocked and closed file lock open on"
                                " `%s`", self.path) 
Example #4
Source File: threadutils.py    From plex-for-kodi with GNU General Public License v2.0 6 votes vote down vote up
def kill(self, force_and_wait=False):
        pass
    #     try:
    #         self._raiseExc(KillThreadException)

    #         if force_and_wait:
    #             time.sleep(0.1)
    #             while self.isAlive():
    #                 self._raiseExc(KillThreadException)
    #                 time.sleep(0.1)
    #     except threading.ThreadError:
    #         pass

    # def onKilled(self):
    #     pass

    # def run(self):
    #     try:
    #         self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
    #     except KillThreadException:
    #         self.onKilled() 
Example #5
Source File: threads.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def _get_my_tid(self):
		"""determines this (self's) thread id"""
		if not self.isAlive():
			raise threading.ThreadError("the thread is not active")

		# do we have it cached?
		if hasattr(self, "_thread_id"):
			return self._thread_id

		# no, look for it in the _active dict
		for tid, tobj in threading._active.items():
			if tobj is self:
				self._thread_id = tid
				return tid

		raise AssertionError("could not determine the thread's id") 
Example #6
Source File: cron_sensor.py    From ARK with MIT License 6 votes vote down vote up
def active(self):
        """
        重载感知器生效函数,加入自动刷新线程的生效操作。

        :return: 无返回
        :rtype: None
        :raises ThreadError: 创建线程失败
        """
        super(CronSensor, self).active()
        try:
            self._reload_thread = threading.Thread(
                target=self._reload)
            self._reload_thread.daemon = True
            self._reload_thread.start()
        except threading.ThreadError as e:
            log.r(e, "create new thread err") 
Example #7
Source File: PupyJob.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def _get_my_tid(self):
		"""determines this (self's) thread id"""
		if not self.isAlive():
			raise threading.ThreadError("the thread is not active")
		
		# do we have it cached?
		if hasattr(self, "_thread_id"):
			return self._thread_id
		
		# no, look for it in the _active dict
		for tid, tobj in threading._active.items():
			if tobj is self:
				self._thread_id = tid
				return tid
		
		raise AssertionError("could not determine the thread's id") 
Example #8
Source File: PupyJob.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def _get_my_tid(self):
		"""determines this (self's) thread id"""
		if not self.isAlive():
			raise threading.ThreadError("the thread is not active")
		
		# do we have it cached?
		if hasattr(self, "_thread_id"):
			return self._thread_id
		
		# no, look for it in the _active dict
		for tid, tobj in threading._active.items():
			if tobj is self:
				self._thread_id = tid
				return tid
		
		raise AssertionError("could not determine the thread's id") 
Example #9
Source File: sapphire_load_manager.py    From grizzly with Mozilla Public License 2.0 6 votes vote down vote up
def start(self):
        assert self._job.pending
        # create the listener thread to handle incoming requests
        listener = threading.Thread(
            target=self.listener,
            args=(self._socket, self._job, self._workers),
            kwargs={"shutdown_delay": self.SHUTDOWN_DELAY})
        # launch listener thread and handle thread errors
        for retry in reversed(range(10)):
            try:
                listener.start()
            except threading.ThreadError:
                # thread errors can be due to low system resources while fuzzing
                LOG.warning("ThreadError (listener), threads: %d", threading.active_count())
                if retry < 1:
                    raise
                time.sleep(1)
                continue
            self._listener = listener
            break 
Example #10
Source File: test_sapphire_worker.py    From grizzly with Mozilla Public License 2.0 6 votes vote down vote up
def test_sapphire_worker_03(mocker):
    """test SapphireWorker.launch() fail cases"""
    serv_con = mocker.Mock(spec=socket.socket)
    serv_job = mocker.Mock(spec=SapphireJob)
    fake_thread = mocker.patch("sapphire.sapphire_worker.threading.Thread", autospec=True)
    mocker.patch("sapphire.sapphire_worker.time.sleep", autospec=True)

    serv_con.accept.side_effect = socket.timeout
    assert SapphireWorker.launch(serv_con, serv_job) is None

    serv_con.accept.side_effect = None
    conn = mocker.Mock(spec=socket.socket)
    serv_con.accept.return_value = (conn, None)
    fake_thread.side_effect = threading.ThreadError
    assert SapphireWorker.launch(serv_con, serv_job) is None
    assert conn.close.call_count == 1
    assert serv_job.accepting.clear.call_count == 0
    assert serv_job.accepting.set.call_count == 1 
Example #11
Source File: sapphire_worker.py    From grizzly with Mozilla Public License 2.0 6 votes vote down vote up
def launch(cls, listen_sock, job):
        assert job.accepting.is_set()
        conn = None
        try:
            conn, _ = listen_sock.accept()
            conn.settimeout(None)
            # create a worker thread to handle client request
            w_thread = threading.Thread(target=cls.handle_request, args=(conn, job))
            job.accepting.clear()
            w_thread.start()
            return cls(conn, w_thread)
        except (socket.error, socket.timeout):
            if conn is not None:  # pragma: no cover
                conn.close()
        except threading.ThreadError:
            if conn is not None:  # pragma: no cover
                conn.close()
            # reset accepting status
            job.accepting.set()
            LOG.warning("ThreadError (worker), threads: %d", threading.active_count())
            # wait for system resources to free up
            time.sleep(0.1)
        return None 
Example #12
Source File: default.py    From script.service.kodi.callbacks with GNU General Public License v3.0 6 votes vote down vote up
def abortall():
    for p in Cache.publishers:
        try:
            p.abort()
        except threading.ThreadError as e:
            log(msg=_('Error aborting: %s - Error: %s') % (str(p), str(e)))
    Cache.dispatcher.abort()
    for p in Cache.publishers:
        p.join(0.5)
    Cache.dispatcher.join(0.5)
    if len(threading.enumerate()) > 1:
        main_thread = threading.current_thread()
        log(msg=_('Enumerating threads to kill others than main (%i)') % main_thread.ident)
        for t in threading.enumerate():
            if t is not main_thread and t.is_alive():
                log(msg=_('Attempting to kill thread: %i: %s') % (t.ident, t.name))
                try:
                    t.abort(0.5)
                except (threading.ThreadError, AttributeError):
                    log(msg=_('Error killing thread'))
                else:
                    if not t.is_alive():
                        log(msg=_('Thread killed succesfully'))
                    else:
                        log(msg=_('Error killing thread')) 
Example #13
Source File: audio_player.py    From sed_vis with MIT License 6 votes vote down vote up
def close(self):
        """
        Destructor for this audio interface. Waits the threads to finish their
        streams, if desired.
        """
        with self.halting:  # Avoid simultaneous "close" threads

            if not self.finished:  # Ignore all "close" calls, but the first,
                self.finished = True  # and any call to play would raise ThreadError

                # Closes all playing AudioThread instances
                while True:
                    with self.lock:  # Ensure there's no other thread messing around
                        try:
                            thread = self._threads[0]  # Needless to say: pop = deadlock
                        except IndexError:  # Empty list
                            break  # No more threads

                    thread.stop()
                    thread.join()

                # Finishes
                assert not self._pa._streams  # No stream should survive
                self._pa.terminate() 
Example #14
Source File: audio_player.py    From sed_vis with MIT License 6 votes vote down vote up
def play(self, offset=0.0, duration=None):
        """
        Start another thread playing the given audio sample iterable (e.g. a
        list, a generator, a NumPy np.ndarray with samples), and play it.
        The arguments are used to customize behaviour of the new thread, as
        parameters directly sent to PyAudio's new stream opening method, see
        AudioThread.__init__ for more.
        """
        if self.playing:
            # If playback is on, stop play
            self.stop()

        with self.lock:
            if self.finished:
                raise threading.ThreadError("Trying to play an audio stream while "
                                            "halting the AudioIO manager object")
            self.player_thread = AudioThread(device_manager=self,
                                             audio=self.get_segment(offset, duration),
                                             chunk_size=2048,
                                             sampling_rate=self.sampling_rate,
                                             nchannels=self.channels)

            self.player_thread.start()
            self.playing = True 
Example #15
Source File: PupyJob.py    From backdoorme with MIT License 6 votes vote down vote up
def _get_my_tid(self):
		"""determines this (self's) thread id"""
		if not self.isAlive():
			raise threading.ThreadError("the thread is not active")
		
		# do we have it cached?
		if hasattr(self, "_thread_id"):
			return self._thread_id
		
		# no, look for it in the _active dict
		for tid, tobj in threading._active.items():
			if tobj is self:
				self._thread_id = tid
				return tid
		
		raise AssertionError("could not determine the thread's id") 
Example #16
Source File: base.py    From dataflow with Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        self._succ = self._lock.acquire(False)
        if not self._succ:
            raise threading.ThreadError("This DataFlow is not reentrant!") 
Example #17
Source File: ltmain.py    From Python with MIT License 5 votes vote down vote up
def _get_my_tid(self):
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        if hasattr(self, "_thread_id"):
            return self._thread_id

        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        raise AssertionError("could not determine the thread's id") 
Example #18
Source File: connection.py    From azure-uamqp-python with MIT License 5 votes vote down vote up
def release(self):
        try:
            self._lock.release()
        except (RuntimeError, threading.ThreadError):
            pass
        except:
            _logger.debug("Got error when attempting to release connection lock.")
            try:
                self._lock.release()
            except (RuntimeError, threading.ThreadError):
                pass
            raise 
Example #19
Source File: test_multiprocessing.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example #20
Source File: process_lock.py    From fasteners with Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        gotten = self.acquire()
        if not gotten:
            # This shouldn't happen, but just incase...
            raise threading.ThreadError("Unable to acquire a file lock"
                                        " on `%s` (when used as a"
                                        " context manager)" % self.path)
        return self 
Example #21
Source File: test_process_lock.py    From fasteners with Apache License 2.0 5 votes vote down vote up
def test_bad_acquire(self):
        lock_file = os.path.join(self.lock_dir, 'lock')
        lock = BrokenLock(lock_file, errno.EBUSY)
        self.assertRaises(threading.ThreadError, lock.acquire) 
Example #22
Source File: test_multiprocessing.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example #23
Source File: test_multiprocessing.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example #24
Source File: test_threadworker.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def release(self):
        """
        Release the lock.  Raise an exception if the lock is not presently
        acquired.
        """
        if not self.acquired:
            raise ThreadError()
        self.acquired = False 
Example #25
Source File: test_threadworker.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_fakeDoubleRelease(self):
        """
        The L{FakeLock} test fixture will alert us if there's a potential
        double-release.
        """
        lock = FakeLock()
        self.assertRaises(ThreadError, lock.release)
        lock.acquire()
        self.assertEqual(None, lock.release())
        self.assertRaises(ThreadError, lock.release) 
Example #26
Source File: automaton.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def call_release(self, arborted=False):
        """DEV: Must be call when the object becomes ready to read.
           Relesases the lock of _wait_non_ressources"""
        self.was_ended = arborted
        try:
            self.trigger.release()
        except (threading.ThreadError, AttributeError):
            pass
        # Trigger hooks
        for hook in self.hooks:
            hook() 
Example #27
Source File: data_provider.py    From tf-cpn with MIT License 5 votes vote down vote up
def __enter__(self):
        self._succ = self._lock.acquire(False)
        if not self._succ:
            raise threading.ThreadError("This DataFlow is not reentrant!") 
Example #28
Source File: test_threading.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread 
Example #29
Source File: _test_multiprocessing.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example #30
Source File: sensor.py    From ARK with MIT License 5 votes vote down vote up
def active(self):
        """
        感知器生效函数。该函数创建新线程,定期进行外部事件拉取操作

        :return: 无返回
        :rtype: None
        :raises ThreadError: 创建线程失败
        """
        try:
            self._pull_thread = threading.Thread(
                target=self.event_dealer)
            self._pull_thread.daemon = True
            self._pull_thread.start()
        except threading.ThreadError as e:
            log.r(e, "create new thread err")