Start two threads in same time

koranthala koranthala at gmail.com
Fri Jan 16 09:51:31 EST 2009


On Jan 16, 7:46 pm, koranthala <koranth... at gmail.com> wrote:
> On Jan 16, 7:36 pm, vedrandeko... at gmail.com wrote:
>
> > Hello,
>
> > Does anybody know how can I start two threads in same time?
>
> > Regards,
> > John
>
> Use threading module.
> Creating a new thread is as easy as --
> -----------------------------------------------------------------------
> import threading
>
> class ThreadedClass(threading.Thread):
>     def __init__(self):
>         threading.Thread.__init__(self)
>
>     def run(self):
>          **Do whatever you want do in the new thread here**
>
> threaded_obj = ThreadedClass()
> threaded_obj.setDaemon(True)  # If you want a daemon thread
> threaded_obj.start() # Start the new thread
>
> %%%%Do whatever you want to do in main thread here%%%
>
> threaded_obj.join() #Close the new thread by joining it with the main
> thread
>
> --------------------------------------------------------------------------------
>
> The following document might be of help:http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf

If you want to create n threads, just create and call the threaded_obj
n times.
So, the code will look like:

threaded_obj = []

for i in range(n):
   threaded_obj[i] = ThreadedClass()
   threaded_obj[i].setDaemon(True)  # If you want a daemon thread
   threaded_obj[i].start() # Start the new thread

%%%%Do whatever you want to do in main thread here%%%

#To close the threads
for o in threaded_obj:
   o.join()

--HTH--



More information about the Python-list mailing list