Python threading.activeCount() Examples

The following are 30 code examples for showing how to use threading.activeCount(). 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: cherrypy   Author: cherrypy   File: plugins.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start(self):
        if self.finalized:
            self.bus.log('Already deamonized.')

        # forking has issues with threads:
        # http://www.opengroup.org/onlinepubs/000095399/functions/fork.html
        # "The general problem with making fork() work in a multi-threaded
        #  world is what to do with all of the threads..."
        # So we check for active threads:
        if threading.activeCount() != 1:
            self.bus.log('There are %r active threads. '
                         'Daemonizing now may cause strange failures.' %
                         threading.enumerate(), level=30)

        self.daemonize(self.stdin, self.stdout, self.stderr, self.bus.log)

        self.finalized = True 
Example 2
Project: HeartLeak   Author: OffensivePython   File: HeartLeak.py    License: MIT License 6 votes vote down vote up
def scan(nhost, port, nthread):
    hFile=open("heartleaked.log", "a")
    global n
    print("[+] Running a scan to find %d vulnerable host(s). Be patient!"%nhost)
    n=nhost
    while n>0:
        try:
            ip=randomHost()
            try:
                while threading.activeCount()>nthread:
                    time.sleep(5)
                t=threading.Thread(target=leakTest, args=(hFile, ip, port))
                t.start()
            except:
                time.sleep(5)
        except KeyboardInterrupt:
            print("[-] Cancelled due to keyboard interruption")
            break
    hFile.close()
    return 
Example 3
Project: smarthome   Author: smarthomeNG   File: smarthome.py    License: GNU General Public License v3.0 6 votes vote down vote up
def list_threads(self, txt):

        cp_threads = 0
        http_threads = 0
        for thread in threading.enumerate():
            if thread.name.find("CP Server") == 0:
                cp_threads += 1
            if thread.name.find("HTTPServer") == 0:
                http_threads +=1

        self._logger.info("list_threads: {} - Number of Threads: {} (CP Server={}, HTTPServer={}".format(txt, threading.activeCount(), cp_threads, http_threads))
        for thread in threading.enumerate():
            if thread.name.find("CP Server") != 0 and thread.name.find("HTTPServer") != 0:
                self._logger.info("list_threads: {} - Thread {}".format(txt, thread.name))
        return


    #################################################################
    # Item Methods
    ################################################################# 
Example 4
Project: MARA_Framework   Author: xtiankisutsa   File: pyssltest.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def status():
	ready = 0
	inva = 0
	errc = 0
	pend = 0
	print '\n' * 100
	for key in jobtrack:
			if jobtrack[key] =="Not Tested":
				pend = pend + 1
			elif jobtrack[key] =="Invalid":
				inva = inva + 1
			elif jobtrack[key] =="ERROR":
				errc = errc + 1
			elif jobtrack[key] =="READY":
				ready = ready + 1
	print "\n There are " + str(pend) + " pending"
	print "\n There are " + str(inva) + " Invalid"
	print "\n There are " + str(errc) + " errors"
	print "\n There are " + str(ready) + " ready"
	print "\n There are " + str(threading.activeCount()) + " Threads" 
Example 5
Project: pysoxy   Author: MisterDaneel   File: pysoxy.py    License: GNU General Public License v2.0 6 votes vote down vote up
def main():
    """ Main function """
    new_socket = create_socket()
    bind_port(new_socket)
    signal(SIGINT, exit_handler)
    signal(SIGTERM, exit_handler)
    while not EXIT.get_status():
        if activeCount() > MAX_THREADS:
            sleep(3)
            continue
        try:
            wrapper, _ = new_socket.accept()
            wrapper.setblocking(1)
        except socket.timeout:
            continue
        except socket.error:
            error()
            continue
        except TypeError:
            error()
            sys.exit(0)
        recv_thread = Thread(target=connection, args=(wrapper, ))
        recv_thread.start()
    new_socket.close() 
Example 6
Project: LightUpPi-Alarm   Author: carlosperate   File: AlarmManager_test.py    License: MIT License 6 votes vote down vote up
def test_set_alarm_thread_edit(self):
        """
        Tests the __set_alarm_thread when an existing alarm thread is inputted.
        No need to check for input with wrong ID as that gets dealt with in the
        AlarmThread class and unit test.
        """
        first_alarm = AlarmItem(self.hour, 34, label='test', alarm_id=96,
                                days=(True, True, True, True, True, True, True),
                                enabled=True)
        new_alarm = AlarmItem(self.hour, 34, enabled=False, alarm_id=96,
                              label='test replace',
                              days=(False, False, False, False, False, False,
                                    False))
        alarm_mgr = AlarmManager()
        alarm_mgr.delete_all_alarms()
        numb_threads = threading.activeCount()
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(first_alarm)
        self.assertTrue(launch_success)
        self.assertGreater(threading.activeCount(), numb_threads)

        # Editing to the new alarm data should stop the thread as it is inactive
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(new_alarm)
        self.assertFalse(launch_success)
        self.assertEqual(threading.activeCount(), numb_threads) 
Example 7
Project: LightUpPi-Alarm   Author: carlosperate   File: AlarmManager_test.py    License: MIT License 6 votes vote down vote up
def test_stop_alarm_thread(self):
        """
        Test that the __stop_alarm_thread private method will stop a running
        Alarm Thread, which due to the nature of the thread code can take up to
        10 seconds.
        This test accesses private methods.
        """
        alarm = AlarmItem(self.hour, 34, enabled=True, label='t', alarm_id=96,
                          days=(False, True, True, True, True, True, True))
        alarm_mgr = AlarmManager()
        alarm_mgr.delete_all_alarms()
        numb_threads = threading.activeCount()
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm)
        self.assertTrue(launch_success)
        self.assertGreater(threading.activeCount(), numb_threads)
        stop_success = alarm_mgr._AlarmManager__stop_alarm_thread(alarm.id_)
        self.assertTrue(stop_success)
        self.assertEqual(threading.activeCount(), numb_threads) 
Example 8
Project: LightUpPi-Alarm   Author: carlosperate   File: AlarmManager_test.py    License: MIT License 6 votes vote down vote up
def test_stop_all_alarm_threads(self):
        """
        Launches 2 alarms threads, checks they are running and them stops them
        all and checks again.
        """
        alarm_one = AlarmItem(
            self.hour, 34, enabled=True, alarm_id=31,
            days=(False, False, False, False, False, False, True))
        alarm_two = AlarmItem(
            self.hour, 34, enabled=True, alarm_id=32,
            days=(False, False, False, False, False, False, True))
        alarm_mgr = AlarmManager()
        # There is a bit of circular dependency here as delete all will execute
        # __stop_all_alarm_threads
        alarm_mgr.delete_all_alarms()
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm_one)
        self.assertTrue(launch_success)
        launch_success = alarm_mgr._AlarmManager__set_alarm_thread(alarm_two)
        self.assertTrue(launch_success)
        numb_threads = threading.activeCount()
        self.assertGreaterEqual(numb_threads, 2)
        delete_success = alarm_mgr._AlarmManager__stop_all_alarm_threads()
        self.assertTrue(delete_success)
        self.assertEqual(threading.activeCount(), numb_threads - 2) 
Example 9
Project: F-Scrack   Author: y1ng1996   File: F-Scrack.py    License: GNU General Public License v3.0 6 votes vote down vote up
def t_join(m_count):
    tmp_count = 0
    i = 0
    if I < m_count:
        count = len(ip_list) + 1
    else:
        count = m_count
    while True:
        time.sleep(4)
        ac_count = threading.activeCount()
        #print ac_count,count
        if ac_count < count  and ac_count == tmp_count:
            i+=1
        else:
            i=0
        tmp_count = ac_count
        #print ac_count,queue.qsize()
        if (queue.empty() and threading.activeCount() <= 1) or i > 5:
            break 
Example 10
Project: nullinux   Author: m8r0wn   File: nullinux.py    License: MIT License 6 votes vote down vote up
def rid_cycling(self, target, ridrange, max_threads):
        print("\n\033[1;34m[*]\033[1;m Performing RID Cycling for: {}".format(target))
        if not self.domain_sid:
            print_failure("RID Failed: Could not attain Domain SID")
            return False
        # Handle custom RID range input
        try:
            r = ridrange.split("-")
            rid_range = list(range(int(r[0]), int(r[1])+1))
        except:
            print_failure("Error parsing custom RID range, reverting to default")
            rid_range = list(range(500, 551))
        for rid in rid_range:
            try:
                Thread(target=self.rid_thread, args=(rid,target,), daemon=True).start()
            except:
                pass
            while activeCount() > max_threads:
                sleep(0.001)
        while activeCount() > 1:
            sleep(0.001) 
Example 11
Project: F-Scrack   Author: qianniaoge   File: F-Scrack.py    License: GNU General Public License v3.0 6 votes vote down vote up
def t_join(m_count):
    tmp_count = 0
    i = 0
    if I < m_count:
        count = len(ip_list) + 1
    else:
        count = m_count
    while True:
        time.sleep(4)
        ac_count = threading.activeCount()
        #print ac_count,count
        if ac_count < count  and ac_count == tmp_count:
            i+=1
        else:
            i=0
        tmp_count = ac_count
        #print ac_count,queue.qsize()
        if (queue.empty() and threading.activeCount() <= 1) or i > 5:
            break 
Example 12
Project: enumdb   Author: m8r0wn   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def launcher(args):
    try:
        if args.shell:
            print_status("Initiating SQL shell..")
            shell_launcher(args)
        else:
            print_status("Starting enumeration...")
            print_status("Users  : {}".format(len(args.users)))
            print_status("Targets: {}".format(len(args.target)))
            print_status("Time   : {}\n".format(datetime.now().strftime('%m-%d-%Y %H:%M:%S')))
            for t in args.target:
                x = Thread(target=enum_db().db_main, args=(args, t,))
                x.daemon = True
                x.start()
                # Do not exceed max threads
                while activeCount() > args.max_threads:
                    sleep(0.001)
            # Exit all threads before closing
            while activeCount() > 1:
                sleep(0.001)
    except KeyboardInterrupt:
        print("\n[!] Key Event Detected...\n\n")
        exit(0) 
Example 13
Project: Tautulli   Author: Tautulli   File: plugins.py    License: GNU General Public License v3.0 6 votes vote down vote up
def start(self):
        if self.finalized:
            self.bus.log('Already deamonized.')

        # forking has issues with threads:
        # http://www.opengroup.org/onlinepubs/000095399/functions/fork.html
        # "The general problem with making fork() work in a multi-threaded
        #  world is what to do with all of the threads..."
        # So we check for active threads:
        if threading.activeCount() != 1:
            self.bus.log('There are %r active threads. '
                         'Daemonizing now may cause strange failures.' %
                         threading.enumerate(), level=30)

        self.daemonize(self.stdin, self.stdout, self.stderr, self.bus.log)

        self.finalized = True 
Example 14
Project: Tango   Author: autolab   File: tango.py    License: Apache License 2.0 6 votes vote down vote up
def getInfo(self):
        """ getInfo - return various statistics about the Tango daemon
        """
        stats = {}
        stats['elapsed_secs'] = time.time() - self.start_time;
        stats['job_requests'] = Config.job_requests
        stats['job_retries'] = Config.job_retries
        stats['waitvm_timeouts'] = Config.waitvm_timeouts
        stats['runjob_timeouts'] = Config.runjob_timeouts
        stats['copyin_errors'] = Config.copyin_errors
        stats['runjob_errors'] = Config.runjob_errors
        stats['copyout_errors'] = Config.copyout_errors
        stats['num_threads'] = threading.activeCount()
        
        return stats

    #
    # Helper functions
    # 
Example 15
Project: Forager   Author: opensourcesec   File: Forager.py    License: MIT License 5 votes vote down vote up
def run_modules():
    x = FeedModules()
    threads = []
    for i in dir(x):
        if i.endswith('_update'):
            mod = getattr(x, i)
            threads.append(Thread(target=mod, name='{}'.format(i)))
        else:
            pass

    for t in threads:
        t.start()
        print('Initialized: {}'.format(t.name))

    sleep(3)
    stat = 0.0
    total = float(len(threads))

    tcount = activeCount()
    while tcount > 1:
        stat = total - float(activeCount()) + 1.0
        prog = stat/total
        update_progress(prog)
        tcount = activeCount()
        sleep(1)
    print((Fore.GREEN + '\n[+]' + Fore.RESET + ' Feed collection finished!')) 
Example 16
Project: avocado-vt   Author: avocado-framework   File: virtio_console_guest.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_alive():
    """
    Check is only main thread is alive and if guest react.
    """
    if ((os_linux and (threading.activeCount() == 2)) or
            ((not os_linux) and (threading.activeCount() == 1))):
        print("PASS: Guest is ok no thread alive")
    else:
        threads = ""
        for thread in threading.enumerate():
            threads += thread.name + ", "
        print("FAIL: On guest run thread. Active thread:" + threads) 
Example 17
Project: subscraper   Author: m8r0wn   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def takeover(args, targets):
    stdout.write("\n\033[1;30m[*] Subdomain Takeover Check\033[1;m\n")
    stdout.write("\033[1;30m{:<45}\t({:<9})\t{}\033[1;m\n".format('Subdomain', 'http/https', 'CNAME Record'))
    try:
        for target in targets:
            Thread(target=takeover_check, args=(target,), daemon=True).start()
            while activeCount() > args.max_threads:
                sleep(0.001)
        while activeCount() > 1:
            sleep(0.005)
    except KeyboardInterrupt:
        stdout.write("\n[!] Key Event Detected...\n\n")
        return 
Example 18
Project: python-duckling   Author: FraBle   File: duckling.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 jvm_started=False,
                 parse_datetime=False,
                 minimum_heap_size='128m',
                 maximum_heap_size='2048m'):
        """Initializes Duckling.
        """

        self.parse_datetime = parse_datetime
        self._is_loaded = False
        self._lock = threading.Lock()

        if not jvm_started:
            self._classpath = self._create_classpath()
            self._start_jvm(minimum_heap_size, maximum_heap_size)

        try:
            # make it thread-safe
            if threading.activeCount() > 1:
                if not jpype.isThreadAttachedToJVM():
                    jpype.attachThreadToJVM()
            self._lock.acquire()

            self.clojure = jpype.JClass('clojure.java.api.Clojure')
            # require the duckling Clojure lib
            require = self.clojure.var("clojure.core", "require")
            require.invoke(self.clojure.read("duckling.core"))
        finally:
            self._lock.release() 
Example 19
Project: oss-ftp   Author: aliyun   File: servers.py    License: MIT License 5 votes vote down vote up
def _map_len(self):
            return threading.activeCount() 
Example 20
Project: oss-ftp   Author: aliyun   File: servers.py    License: MIT License 5 votes vote down vote up
def _map_len(self):
            return threading.activeCount() 
Example 21
Project: pythonprojects   Author: kurtlab   File: imagesmake.py    License: MIT License 5 votes vote down vote up
def downloadPic(self, urls, path):

        # 每过三秒检查一次当前正在运行的线程数,超标则沉睡等待线程结束
        while threading.activeCount() > 200:
            print("线程超标---%s" % threading.activeCount())
            time.sleep(3)

        for url in urls:
            if url:
                self.download(url, path) 
Example 22
Project: pythonprojects   Author: kurtlab   File: download_cl1024_images.py    License: MIT License 5 votes vote down vote up
def downloadPic(self, urls, path):

        # 每过三秒检查一次当前正在运行的线程数,超标则沉睡等待线程结束
        while threading.activeCount() > 5:
            print("线程超标---%s" % threading.activeCount())
            time.sleep(3)

        for url in urls:
            if url:
                print(url)
                self.download(url, path) 
Example 23
Project: stack   Author: bitslabsyr   File: processes.py    License: MIT License 5 votes vote down vote up
def go(self):
        """
        Starts and maintains the loop that monitors the collection thread.
        Threads are maintained in the extended versions of the class
        """
        # Checks if we're supposed to be running
        self.run_flag = self.check_flags()['run']
        self.collect_flag = 0
        self.update_flag = 0

        if self.run_flag:
            self.log('Starting Facebook collector %s with signal %d' % (self.process_name, self.run_flag))
            self.set_active(1)

        # If run_flag is set - begin the loop
        while self.run_flag:
            try:
                flags = self.check_flags()
                self.run_flag = flags['run']
                self.collect_flag = flags['collect']
                self.update_flag = flags['update']
            except Exception as e:
                self.log('Mongo connection refused with exception: %s' % e, level='warn')

            # If we've been flagged to stop or update and we're collecting - shut it down
            if self.collecting_data and (self.update_flag or not self.collect_flag or not self.run_flag):
                self.stop_thread()

            # If we've been flagged to start and we're not collecting - start it up
            if self.collect_flag and threading.activeCount() == 1:
                self.start_thread()

            time.sleep(2)

        self.log('Exiting Facebook collection.')
        self.set_active(0) 
Example 24
Project: Fluid-Designer   Author: Microvellum   File: test_threading.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_old_threading_api(self):
        # Just a quick sanity check to make sure the old method names are
        # still present
        t = threading.Thread()
        t.isDaemon()
        t.setDaemon(True)
        t.getName()
        t.setName("name")
        t.isAlive()
        e = threading.Event()
        e.isSet()
        threading.activeCount() 
Example 25
Project: ironpython3   Author: IronLanguages   File: test_threading.py    License: Apache License 2.0 5 votes vote down vote up
def test_old_threading_api(self):
        # Just a quick sanity check to make sure the old method names are
        # still present
        t = threading.Thread()
        t.isDaemon()
        t.setDaemon(True)
        t.getName()
        t.setName("name")
        t.isAlive()
        e = threading.Event()
        e.isSet()
        threading.activeCount() 
Example 26
Project: code   Author: ActiveState   File: recipe-578193.py    License: MIT License 5 votes vote down vote up
def run(self):
        try:
            url,filename=self.qu1.get()
            url =url+self.ad             #comment this line in case need to download whole web page instead of recipe ONLY...
            ul.urlretrieve(url,filename)
            global count
        except:
            print " RE-TRYING ",
            count= count - 1
            self.qu1.put((url,filename))
            self.run()
        finally:
            count= count +1
            print str(count)+"("+str( threading.activeCount())  +")",filename
            self.qu1.task_done() 
Example 27
Project: agents-aea   Author: fetchai   File: conftest.py    License: Apache License 2.0 5 votes vote down vote up
def check_test_threads(request):
    """Check particular test close all spawned threads."""
    if not request.config.getoption("--check-threads"):
        yield
        return
    if request.cls:
        yield
        return
    num_threads = threading.activeCount()
    yield
    new_num_threads = threading.activeCount()
    assert num_threads >= new_num_threads, "Non closed threads!" 
Example 28
Project: d4rkc0de   Author: knightmare2600   File: pyscan.py    License: GNU General Public License v2.0 5 votes vote down vote up
def scan(self, host, start, stop):
        self.port = start
        while self.port <= stop:
            while threading.activeCount() < MAX_THREADS:
                Scanner(host, self.port).start()
                self.port += 1 
Example 29
Project: lynder   Author: enescakir   File: lynder.py    License: MIT License 5 votes vote down vote up
def download_videos(tutorial):
    for chapter, lectures in tutorial["chapters"].items():
        os.chdir(chapter)
        for index, lecture in enumerate(lectures):
            while(threading.activeCount() > WORKER_NUM):
                time.sleep(5)
            th = Thread(target=download_lecture, args=(lecture,index,))
            th.deamon = True
            th.start()
            th.join()

        os.chdir("..")
    print("DOWNLOADING IS DONE")
    if arguments.silent is None:
        os.system("open .") 
Example 30
Project: tsocks   Author: jun7th   File: tsocks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def exchange_data(self,sock,remote):#forward data
		global DEBUG
		try:
			inputs = [sock, remote]
			while True:
				r, w, e = select.select(inputs, [], [])
				if sock in r:
					if remote.send(sock.recv(BUF_SIZE)) <= 0:
						#sock.shutdown(socket.SHUT_RDWR)
						sock.close()
						#remote.shutdown(socket.SHUT_RDWR)
						remote.close()
						break
				if remote in r:
					if sock.send(remote.recv(BUF_SIZE)) <= 0:
						#sock.shutdown(socket.SHUT_RDWR)
						sock.close()
						#remote.shutdown(socket.SHUT_RDWR)
						remote.close()
						break
					if DEBUG:
						print "[*]Current active thread:",threading.activeCount()
						print "[*]Forwarding data..."
		except Exception,e:
			if DEBUG:
				print e
			sock.send("socket error")
			#remote.shutdown(socket.SHUT_RDWR)
			remote.close()
			#sock.shutdown(socket.SHUT_RDWR)
			sock.close()