threading - Doug Hellman stdlib book, Timer() subclassing etc

Veek. M vek.m1234 at gmail.com
Wed Feb 17 00:36:30 EST 2016


In Doug Hellman's book on the stdlib, he does:

import threading
import logging
logging.basicConfig(level=logging.DEBUG,
    format=’(%(threadName)-10s) %(message)s’,
)

class MyThreadWithArgs(threading.Thread):
    def __init__(self, group=None, target=None, name=None,
        args=(), kwargs=None, verbose=None):

        threading.Thread.__init__(self, group=group,
            target=target,
            name=name,
            verbose=verbose)

        self.args = args
        self.kwargs = kwargs
        return

    def run(self):
        logging.debug(’running with %s and %s’,
        self.args, self.kwargs)
        return

    for i in range(5):
        t = MyThreadWithArgs(args=(i,), kwargs={’a’:’A’, ’b’:’B’})
        t.start()

1. Shouldn't def run() also include a call to the target function?
2. How does a call to a function_target result in a thread being 
created? Normally you'd have to call a function in pthreads (OS call)
One can sort of figure that t.start() hides the actual OS call, but when
we implement run().. somehow, magically there's no OS call? WTH! ??

Then in the Timer example in the next section, how is
the whole delay/canecl bit implemented?
We do t1.start so the 3 second counter starts ticking somewhere
- where? And how does he cancel that?

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
    format=’(%(threadName)-10s) %(message)s’,
)

def delayed():
    logging.debug(’worker running’)
    return

t1 = threading.Timer(3, delayed)
t1.setName(’t1’)

t2 = threading.Timer(3, delayed)
t2.setName(’t2’)

logging.debug(’starting timers’)

t1.start()
t2.start()

logging.debug(’waiting before canceling %s’, t2.getName())
time.sleep(2)

logging.debug(’canceling %s’, t2.getName())
t2.cancel()

logging.debug(’done’)



More information about the Python-list mailing list