Start two threads in same time

V

vedrandekovic

Hello,

Does anybody know how can I start two threads in same time?

Regards,
John
 
K

koranthala

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
 
K

koranthala

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

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 = 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%%%

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

--HTH--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,299
Messages
2,571,545
Members
48,299
Latest member
Ruby87897

Latest Threads

Top