thread module

James Logajan JamesL at Lugoj.Com
Mon Jul 23 23:24:47 EDT 2001


TheDustbustr wrote:
> 
> What args are encessary when you call thread.start_new_thread()?  The module
> index says:
> 
> "start_new_thread (function, args[, kwargs])
> Start a new thread. The thread executes the function function with the argument
> list args (which must be a tuple). The optional kwargs argument specifies a
> dictionary of keyword arguments."
> 
> How do I create a simple thread like so:
> def hi():
>   print "Hi!"
> thread.start_new_thread(hi(),args)
> 
> What are the args?

Since the function hi() takes no arguments, the "args" argument should be an
empty tuple, which is represented by an open and close parenthesis. Also,
the "function" argument should be just the function name WITHOUT the
parenthesis. You used "hi()" when you should have simply used "hi". So to
start the thread, you would do:

thread.start_new_thread(hi, ())

Here is, hopefully, a more revealing example: Suppose you want two threads
running, one of which prints multiples of 2 every 5 seconds and another that
prints multiple of 3 every 10 seconds. So first define a function that takes
an identifier, the time to wait, and the amount by which to increment, and
then use it to launch two threads:

import thread
import time

def Func(id, numSecs, incBy):
    val = 0
    while 1:
        print id, val
        val = val + incBy
        time.sleep(numSecs)

thread.start_new_thread(Func, ("First thread", 5.0, 2))
thread.start_new_thread(Func, ("Second thread", 10.0, 3))


Hope this helps!



More information about the Python-list mailing list