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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: base.py    From ADL 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 #17
Source File: checkip.py    From checkgoogleip with Apache License 2.0 5 votes vote down vote up
def checksingleprocess(ipqueue,cacheResult,max_threads):
    threadlist = []
    threading.stack_size(96 * 1024)
    PRINT('need create max threads count: %d' % (max_threads))
    for i in xrange(1, max_threads + 1):
        ping_thread = Ping(ipqueue,cacheResult)
        ping_thread.setDaemon(True)
        try:
            ping_thread.start()
        except threading.ThreadError as e:
            PRINT('start new thread except: %s,work thread cnt: %d' % (e, Ping.getCount()))
            break
        threadlist.append(ping_thread)
    try:
        quit = False
        while not quit:
            for p in threadlist:
                if p.is_alive():
                    p.join(5)
                elif Ping.getCount() == 0 or cacheResult.queryfinish():
                    quit = True
                    break
    except KeyboardInterrupt:
        PRINT("try to interrupt process")
        ipqueue.queue.clear()
        evt_ipramdomend.set()
    cacheResult.close() 
Example #18
Source File: test_multiprocessing.py    From gcblue with BSD 3-Clause "New" or "Revised" 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 #19
Source File: data_provider.py    From lighttrack 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 #20
Source File: data_provider.py    From PoseFix_RELEASE 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 #21
Source File: default.py    From script.service.kodi.callbacks with GNU General Public License v3.0 5 votes vote down vote up
def start():
    global log
    settings = Settings()
    settings.getSettings()
    kl = KodiLogger()
    if settings.general['elevate_loglevel'] is True:
        kl.setLogLevel(xbmc.LOGNOTICE)
    else:
        kl.setLogLevel(xbmc.LOGDEBUG)
    log = kl.log
    log(msg=_('Settings read'))
    Cache.dispatcher = PubSub_Threaded.Dispatcher(interval=settings.general['TaskFreq'], sleepfxn=xbmc.sleep)
    log(msg=_('Dispatcher initialized'))

    subscriberfactory = SubscriberFactory(settings, kl)
    subscribers = subscriberfactory.createSubscribers()
    for subscriber in subscribers:
        Cache.dispatcher.addSubscriber(subscriber)
    publisherfactory = PublisherFactory(settings, subscriberfactory.topics, Cache.dispatcher, kl, debug)
    publisherfactory.createPublishers()
    Cache.publishers = publisherfactory.ipublishers

    Cache.dispatcher.start()
    log(msg=_('Dispatcher started'))

    for p in Cache.publishers:
        try:
            p.start()
        except threading.ThreadError:
            raise
    log(msg=_('Publisher(s) started')) 
Example #22
Source File: test_threading.py    From Project-New-Reign---Nemesis-Main 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 #23
Source File: _test_multiprocessing.py    From Project-New-Reign---Nemesis-Main 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 #24
Source File: test_threading.py    From ironpython3 with Apache License 2.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 #25
Source File: test_multiprocessing.py    From CTFCrackTools-V2 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 #26
Source File: tornadohttpclient.py    From robot with MIT License 5 votes vote down vote up
def _fetch(self, request, callback, kwargs, delay):
        if isinstance(threading.currentThread(), threading._MainThread):
            raise threading.ThreadError, "Can't run this function in _MainThread"
        time.sleep(delay)
        self.fetch(request, callback, **kwargs) 
Example #27
Source File: background_tasks.py    From PerfKitBenchmarker with Apache License 2.0 5 votes vote down vote up
def _SignalAvailableItem(self):
    try:
      self._lock.release()
    except threading.ThreadError:
      pass 
Example #28
Source File: data_provider.py    From video-to-pose3D 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 #29
Source File: test_threading.py    From android_universal with MIT License 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 #30
Source File: test_threading.py    From android_universal with MIT License 5 votes vote down vote up
def test__all__(self):
        extra = {"ThreadError"}
        blacklist = {'currentThread', 'activeCount'}
        support.check__all__(self, threading, ('threading', '_thread'),
                             extra=extra, blacklist=blacklist)