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


Python Thread.is_alive方法代码示例

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


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

示例1: test_term_thread

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
    def test_term_thread(self):
        """ctx.term should not crash active threads (#139)"""
        ctx = zmq.Context()

        def block():
            s = ctx.socket(zmq.REP)
            s.bind_to_random_port("tcp://127.0.0.1")
            try:
                s.recv()
            except zmq.ZMQError:
                e = sys.exc_info()[1]
                if e.errno == zmq.ETERM:
                    # context terminated, this is supposed to happen
                    pass
                else:
                    raise
            s.close()

        t = Thread(target=block)
        t.start()
        if sys.version[:3] == "2.5":
            t.is_alive = t.isAlive
        ctx.term()
        t.join(timeout=1)
        self.assertFalse(t.is_alive(), "term should have interrupted s.recv()")
开发者ID:HVF,项目名称:pyzmq,代码行数:27,代码来源:test_context.py

示例2: test_don_quixote_dictionary

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
    def test_don_quixote_dictionary(self):
        archive_file, output_file = gen_archive_output_pair(
            'don_quixote_dictionary')

        don = DonQuixote(
            blueprints={"blueprints": [
                {
                    "service": "cli_emitter",
                    "args": "-f "
                            "test_data/inputs/don_quixote_dictionary._input"
                            " --output_sock_url tcp://*:9997 -d 0"
                },
                {
                    "service": "cli_listener",
                    "args": "-f "
                            "test_out/don_quixote_dictionary._output"
                            " --input_sock_url tcp://localhost:9997"
                }
            ]},
            disable_keyboard=True)
        assert don

        t = Thread(target=don.run)
        t.start()
        time.sleep(2)
        assert t.is_alive()
        don.kill()
        t.join(2)
        assert not t.is_alive()

        self.assertFiles(archive_file, output_file)
开发者ID:neoinsanity,项目名称:windmills,代码行数:33,代码来源:test_don_quixote.py

示例3: Timer

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
class Timer():
    def __init__(self, delay, target=None):
        if not target is None:
            self.run = target

        self.delay = delay

        self.running = False
        self._t = Thread()

    def _run(self):
        while self.running:
            self.run()
            time.sleep(self.delay)

    def start(self):
        if self._t.is_alive() and not self.running:
            self._t.join()

        if not self._t.is_alive():
            self.running = True
            self._t = Thread(target=self._run)
            self._t.start()

    def pause(self):
        self.running = False
开发者ID:gkraften,项目名称:Gymnasiearbete,代码行数:28,代码来源:timer.py

示例4: test_z_threaded_real_world_run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
  def test_z_threaded_real_world_run(self):
    uid = 1
    jid = 5
    key='stage'
    new_value='done'
    mock_job_data = dict(zip(self.dummy_rtd.valid_keys, self.dummy_rtd.default_values))

    # Setup and verify precondition
    self.dummy_rtd.data = {uid:{jid:mock_job_data}}
    res = self.dummy_rtd.getJob(uid, jid)
    self.assertDictEqual(mock_job_data, res)

    t = Thread(target=self.dummy_rtd.set_attribute, args=(uid, jid, key, new_value))

    self.dummy_rtd.data_lock.acquire()
    t.start()
    time.sleep(1)
    self.assertTrue(t.is_alive())
    self.dummy_rtd.data_lock.release()
    t.join()
    self.assertFalse(t.is_alive())

    # Verify change
    mock_job_data[key]=new_value
    self.assertDictEqual(mock_job_data, self.dummy_rtd.data[uid][jid])
开发者ID:kevinpeizner,项目名称:infinote,代码行数:27,代码来源:test_models.py

示例5: start_forwarder

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
def start_forwarder(conn, addr):
    proxy_addr = random_proxy()
    try:
        s = try_connect(proxy_addr)
    except:
        print('#conn faild')
        sleep(0.1)
        try:
            s = try_connect(proxy_add)
        except:
            #return_proxy(proxy_addr)
            return False
    print('#conn start')
    t1 = Thread(target=data_forward_func(conn, s))
    t2 = Thread(target=data_forward_func(s, conn))
    t1.start()
    t2.start()
    while True:
        if t1.is_alive() and t2.is_alive():
            sleep(0.5)
        else:
            break
    try:
        s.close()
        conn.close()
    except Exception as e:
        print('#close error: ', e)
    print('##conn end')
    return_proxy(proxy_addr)
    return True
开发者ID:Earthson,项目名称:pyproxyforwarder,代码行数:32,代码来源:forwarder.py

示例6: test_direct

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
    def test_direct(self):

        def send_nonblock():
            session = self.publish.direct.get("/test/direct1", {
                                              "type": "direct1",
                                              "message": "hi"},
                                              block=False)
            self.session.resolve(session["message"].id, None)
        thread = Thread(target=send_nonblock, args=())
        thread.daemon = True
        thread.start()
        sleep(0.5)
        self.assertEqual(len(self.session.session_list), 1)
        for session in self.session.session_list.itervalues():
            session["status"] = Status.SENT
            session["is_published"].set()
        thread.join(0.5)
        self.assertFalse(thread.is_alive())

        def send_block():
            self.publish.direct.get("/test/direct2",
                                    {"type": "direct2", "message": "hi"},
                                    block=True)
        thread = Thread(target=send_block, args=())
        thread.daemon = True
        thread.start()
        sleep(0.5)
        self.assertEqual(len(self.session.session_list), 1)
        session = self.session.session_list.values()[0]
        self.session.resolve(session["message"].id, session["mid"])
        thread.join(0.5)
        self.assertFalse(thread.is_alive())
开发者ID:ckgczarzar,项目名称:sanji,代码行数:34,代码来源:test_publish.py

示例7: test_record_lock

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
        def test_record_lock(self):
            shlock = SHLock()
            lock = RecordLock(shlock)

            shlock.acquire()
            self.assertRaises(LockingError, lock.lock, 1)
            shlock.release()
            with lock.lock(1):
                with lock.lock(1):
                    pass

            def dolock():
                with lock.lock(1):
                    time.sleep(0.1)

            t = Thread(target=dolock)
            t.daemon = True
            with lock.lock(1):
                t.start()
                t.join(0.2)
                self.assertTrue(t.is_alive())
            t.join(0.11)
            self.assertFalse(t.is_alive())

            t = Thread(target=dolock)
            t.daemon = True
            with lock.lock(2):
                t.start()
                t.join(0.11)
                self.assertFalse(t.is_alive())
开发者ID:BobPyron,项目名称:calibre,代码行数:32,代码来源:locking.py

示例8: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
    def run(self, input_fname, ids_per_job, stagger=0, **wait_params):
        """Run this submission all the way.

        This method will run both `submit_reading` and `watch_and_wait`,
        blocking on the latter.
        """

        submit_thread = Thread(target=self.submit_reading,
                               args=(input_fname, 0, None, ids_per_job),
                               kwargs={'stagger': stagger},
                               daemon=True)
        submit_thread.start()
        try:
            logger.info("Waiting for just a sec...")
            sleep(1)
            wait_params['wait_for_first_job'] = True
            wait_params['kill_on_exception'] = True
            self.watch_and_wait(**wait_params)
            submit_thread.join(0)
            if submit_thread.is_alive():
                logger.warning("Submit thread is still running even after job "
                               "completion.")
        except BaseException as e:
            logger.error("Watch and wait failed...")
            logger.exception(e)
        finally:
            logger.info("Aborting jobs...")
            # Send a signal to the submission loop (on a thread) to stop.
            self.running = False
            submit_thread.join()
            print(submit_thread.is_alive())

        self.running = None
        return submit_thread
开发者ID:johnbachman,项目名称:indra,代码行数:36,代码来源:submit_reading_pipeline.py

示例9: request

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
def request(method, url, direct_access, argv, app=None):
    global ASGI_APPLICATION
    ret = []
    if direct_access and ASGI_APPLICATION:
        post = True if method == 'post' else False
        h = argv['headers']
        headers = []
        for key, value in h.items():
            headers.append((key.encode('utf-8'), value.encode('utf-8')))
        cookies = ""
        if 'cookies' in argv:
            for key, value in argv['cookies'].items():
                value2 = value.split(';',1)[0]
                cookies += f"{key}={value2};"
        if cookies:
            headers.append((b"cookie", cookies.encode('utf-8')))

        if post:
            t = Thread(target=asgi_get_or_post,
                       args=(ASGI_APPLICATION, url.replace('http://127.0.0.2', ''), headers, argv['data'], post, ret),
                       daemon=True)
            t.start()
            if app:
                try:
                    while t.is_alive():
                        app.Yield()
                except:
                    t.join()
            else:
                t.join()
        else:
            t = Thread(target=asgi_get_or_post,
                       args=(ASGI_APPLICATION, url.replace('http://127.0.0.2', ''), headers, {}, post, ret),
                       daemon=True)
            t.start()
            if app:
                try:
                    while t.is_alive():
                        app.Yield()
                except:
                    t.join()
            else:
                t.join()
        return RetHttp(url, ret[0])
    else:
        if app:
            t = Thread(target=requests_request,
                       args=(method, url, argv, ret),
                       daemon=True)
            t.start()
            try:
                while t.is_alive():
                    app.Yield()
            except:
                t.join()
        else:
            requests_request(method, url, argv, ret)
        return ret[0]
开发者ID:Splawik,项目名称:pytigon,代码行数:60,代码来源:httpclient.py

示例10: Ntp

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
class Ntp(object):

    def __init__(self, model):
        self.model = model
        self._ntp_deamon_event = Event()
        self._ntp_thread = Thread(target=self._ntp_update)
        self._ntp_thread.daemon = True
        if self.model.db["ntp"]["enable"] is True:
            NtpDate(self.model.db["ntp"]["server"])
            self.start()

    def update(self, config):
        # Update config
        self.model.db["ntp"] = dict(
            self.model.db["ntp"].items() + config.items())

        # restart ntp daemon, if enable otherwise stop it.
        self.stop()
        if self.model.db["ntp"]["enable"] is True:
            NtpDate(self.model.db["ntp"]["server"])
            self.start()

        self.model.save_db()
        return True

    def stop(self):
        _logger.debug("stop ntp daemon")
        if self._ntp_thread.is_alive():
            self._ntp_deamon_event.set()
            self._ntp_thread.join()
            # reinitialize Thread Object
            self._ntp_deamon_event.clear()
            self._ntp_thread = Thread(target=self._ntp_update)
            self._ntp_thread.daemon = True
            return True
        return False

    def start(self):
        _logger.debug("start ntp daemon")
        if self._ntp_thread.is_alive():
            raise RuntimeError("Stop previous ntp daemon first.")

        self._ntp_thread.start()

    def _ntp_update(self):
        prev_time = time()
        while not self._ntp_deamon_event.is_set():
            time_diff = math.fabs(prev_time - time())
            if time_diff < self.model.db["ntp"]["interval"]:
                sleep(1)
                continue

            try:
                NtpDate(self.model.db["ntp"]["server"])
            except Exception as e:
                _logger.warning(e)
            finally:
                prev_time = time()
开发者ID:Sanji-IO,项目名称:sanji-bundle-time,代码行数:60,代码来源:ntp.py

示例11: EditDistanceBank

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
class EditDistanceBank():
    def __init__(self, words):
        self.words = words
        self.mapping_table = self._mapping_names(words)
        self.size = len(words)
        self.bank = np.zeros((self.size, self.size), dtype=np.int8)
        self.build_bank_thread = Thread(target=self._build_bank, name='Build editdistance bank')
        self.build_bank_thread.start()
    
    def get_max_distance(self):
        if self.build_bank_thread.is_alive():
            raise EditDistanceBank.InProgressError()
        return self.max_distance
        
    def _mapping_names(self, words):
        mapping = {}
        counter = 0
        for word in words:
            mapping[word] = counter
            counter += 1
        return mapping
    
    def _build_bank(self):
        max_value = 0
        for i in range(self.size - 1):
            for j in range(i + 1, self.size):
                if self.words[i] == '' and self.words[j] == '':
                    self.bank[i][j] = 1
                    self.bank[j][i] = 1
                else:
                    editdistance = levenshtein_dyn(self.words[i], self.words[j])
                    self.bank[i][j] = editdistance
                    self.bank[j][i] = editdistance
                    if max_value < editdistance:
                        max_value = editdistance
        self.max_distance = max_value
        return max_value

    def lookup(self, word1, word2):
        if self.build_bank_thread.is_alive():
            raise EditDistanceBank.InProgressError()
        idx1 = self.mapping_table[word1]
        idx2 = self.mapping_table[word2]
        return self.bank[idx1][idx2]
    
    def join(self):
        if self.build_bank_thread.is_alive():
            self.build_bank_thread.join()

    class InProgressError(Exception):
        def __init__(self):
            pass
            
        def __repr__(self):
            return 'Building edit distance bank in progress, please wait'
开发者ID:duyvk,项目名称:GTVRec,代码行数:57,代码来源:levenshtein.py

示例12: decode_file

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
def decode_file(fname,res):
    if interface != None:
        try:
            p = pcap.pcapObject()
            net, mask = pcap.lookupnet(interface)
            p.open_live(interface, 1600, 0, 100)
            Message = " live capture started, using:%s\nStarting timestamp (%s) corresponds to %s"%(interface, time.time(), time.strftime('%x %X'))
            print Message
            #l.warning(Message)
            while 1:
                p.dispatch(1, Print_Packet_Tcpdump)
        except (KeyboardInterrupt, SystemExit):
            print '\n\nCRTL-C hit...\nCleaning up...'
            sys.exit()
    else:
        try:
            p = pcap.pcapObject()
            p.open_offline(fname)
            #l.warning('\n\n started, using:%s file'%(fname))
            Version = IsCookedPcap(res)
            if Version == 1:
                thread = Thread(target = p.dispatch, args = (0, Print_Packet_Cooked))
                thread.daemon=True
                thread.start()
                try:
                    while thread.is_alive():
                        thread.join(timeout=1)
                except (KeyboardInterrupt, SystemExit):
                    print '\n\nCRTL-C hit..Cleaning up...'
                    threading.Event().set()
            if Version == 2:
                thread = Thread(target = p.dispatch, args = (0, Print_Packet_Cooked))
                thread.daemon=True
                thread.start()
                try:
                    while thread.is_alive():
                        thread.join(timeout=1)
                except (KeyboardInterrupt, SystemExit):
                    print '\n\nCRTL-C hit..Cleaning up...'
                    threading.Event().set()
            if Version == 3:

                thread = Thread(target = p.dispatch, args = (0, Print_Packet_Tcpdump))
                thread.daemon=True
                thread.start()
                try:
                    while thread.is_alive():
                        thread.join(timeout=1)
                except (KeyboardInterrupt, SystemExit):
                    print '\n\nCRTL-C hit..Cleaning up...'
                    threading.Event().set()

        except Exception:
            print 'Can\'t parse %s'%(fname)
开发者ID:bstelte,项目名称:investigate,代码行数:56,代码来源:find-smtp.py

示例13: test_eval_multithreading

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
 def test_eval_multithreading(self):
     ev = Event()
     self.ctx.g.func = ev.wait
     t = Thread(target=self.ctx.eval, args=("func()",))
     t.daemon = True
     t.start()
     t.join(0.01)
     self.assertTrue(t.is_alive())
     ev.set()
     t.join(1)
     self.assertFalse(t.is_alive())
开发者ID:heirecka,项目名称:calibre,代码行数:13,代码来源:tests.py

示例14: test_term_noclose

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
 def test_term_noclose(self):
     """Context.term won't close sockets"""
     ctx = self.Context()
     s = ctx.socket(zmq.REQ)
     self.assertFalse(s.closed)
     t = Thread(target=ctx.term)
     t.start()
     t.join(timeout=0.1)
     self.assertTrue(t.is_alive(), "Context should be waiting")
     s.close()
     t.join(timeout=0.1)
     self.assertFalse(t.is_alive(), "Context should have closed")
开发者ID:JathavanSriram,项目名称:pyzmq,代码行数:14,代码来源:test_context.py

示例15: test_gc

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import is_alive [as 别名]
 def test_gc(self):
     """test close&term by garbage collection alone"""
     # test credit @dln (GH #137):
     def gc():
         ctx = zmq.Context()
         s = ctx.socket(zmq.PUSH)
     t = Thread(target=gc)
     t.start()
     t.join(timeout=1)
     if sys.version[:3] == '2.5':
         t.is_alive = t.isAlive
     self.assertFalse(t.is_alive(), "Garbage collection should have cleaned up context")
开发者ID:aelse,项目名称:pyzmq,代码行数:14,代码来源:test_context.py


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