0

With the following code if I uncomment log_it, threading.active_count reaches 11. Since It means each logger creates _DummyThread daemons.Now

Q1.Is their any way to achieve the same without creating extra threads?

Q2.Why logger needs to create another thread.Why can't it execute in same way, like fun function?

from gevent import monkey
monkey.patch_all()

import threading
import gc
import gevent
import logging

def print_stats():
    while True:
        gc.collect()
        print threading.active_count() 
        gevent.sleep(2)

jobs = [gevent.spawn(print_stats)]
logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.setLevel(logging.INFO)
form = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(form)
logger.addHandler(ch)

def log_it():
    string = 'abcdefghijklmnopqrstuvwxyz'
    logger.info(string)

def fun():
    print "hello world"

def block_for_some_time():
    log_it()
    fun()
    gevent.sleep(5)
    print 'exiting thread'

for i in range(10):
    jobs.append(gevent.spawn(block_for_some_time))

gevent.joinall(jobs)
Pop
  • 12,135
  • 5
  • 55
  • 68
r0h1t4sh
  • 343
  • 2
  • 11

1 Answers1

1

If you change pathcing to this:

from gevent import monkey
monkey.patch_all(thread=False)

threading.active_count() will print 1 all times. The reason is in patching threading module, that provides you with information about "greenlets", not about real threads.

Alexey Kachayev
  • 6,106
  • 27
  • 24