[Tutor] Threads.... More Despair....
Allan Crooks
allan.crooks@btinternet.com
Tue, 12 Jun 2001 01:04:44 +0100
This'll be my first piece of help I've ever given anyone on this list! I'm doing my bit! :)
<snip>
> ## Function write() writes a list to the database
> def write(inputtage):
> time=inputtage[0]
> data_string=inputtage[1]
> db.Execute("insert into data values(%f, '%s')" %(time, data_string))
> return 'ok'
>
> tik_tok=time.time()
> surprize=random.choice(['Hellbilly', 'Crunchy Tack', 'Feeble'])
> the_madness=(tik_tok, surprize)
> thread.start_new_thread(write(the_madness))
>
> gets this error:
>
> Traceback (most recent call last):
> File "dbwrite.py", line 21, in ?
> thread.start_new_thread(write(the_madness))
> TypeError: start_new_thread requires at least 2 arguments; 1 given
>
> Fair enough. I looked again at my spanking new copy of "Python Standard
> Library" and noticed that in the example 'start_new_thread(worker, ())'. In
> the example, worker() does not accept an argument. Hrm.
>
> In the spirit of blind flailing I attempted:
>
> thread.start_new_thread(write(the_madness),())
>
> and got:
>
> Traceback (most recent call last):
> File "dbwrite.py", line 21, in ?
> thread.start_new_thread(write(the_madness), ())
> TypeError: first arg must be callable
>
> for my troubles. Since I don't have a clue what is going on this was not a
> big surprize! :-)
The problem is the slight misunderstanding of what happens when you put:
thread.start_new_thread(write(the_madness),())
What you mean to say is:
thread.start_new_thread(write, (the_madness,)).
The whole point of creating a new thread is to invoke some function. The function may, or may not need arguments.
To create a new thread, you need to supply the function you want to run, and any supplementary arguments.
The function is obviously "write", and the only argument you are supplying is "the_madness". But when you put write(the_madness), the function is actually being executed, and then returns a value (looking at the code, it's the string 'ok'). So:
thread.start_new_thread(write(the_madness),())
is evaluated to:
thread.start_new_thread('ok', ())
and then the thread module complains because it is unable to run the function 'ok' (which is a string, not a function of any sort).
So, once again, the corrected line is:
thread.start_new_thread(write, (the_madness,))
Don't forget that because it's a tuple of one element, it has to have the comma after the first element.
I would try this code out, but I don't have a database to test it on, and in all honesty, I can't be bothered. Hope it works though. :)
Allan.