[Tutor] Thread forever ?

Kent Johnson kent37 at tds.net
Thu Sep 7 12:01:07 CEST 2006


János Juhász wrote:
> 
> Dear Tutors,
> 
> ###################################
> from threading import Thread
> import sys
> import time
> 
> # This thread would read lines from a
> # barcode scanner
> class ComThread(Thread):
>     def __init__(self):
>         Thread.__init__(self)

If you call self.setDaemon() here you will mark the thread as a daemon 
thread and it will not block the exit of the program.

>        
>     def run(self):
>         while 1:
>             time.sleep(2)
>             print time.ctime()
> 
> com = ComThread()
> com.start()
> 
> # Main loop for handling the keyboard
> while 1:
>     s = raw_input()
>     if s == '': continue
>     elif s in 'qQ':
>         # may I com.Terminate() here
>         sys.exit()
>         # when I goes out here
>         # the comthread is just running.
>     else:
>         try:
>             num = int(s)
>             print 'mod qty=%d' % num
>         except:
>             pass
> #################################
> 
> When this program leaves from the while loop, it doesn't terminate the 
> comreader thread.

setDaemon() is the simplest way, as noted above. You could also have the 
main loop set a flag that the thread loop checks; if the flag is set the 
thread loop exits.

Kent



More information about the Tutor mailing list