Understanding thread

Trying to swing our heads. In my code, it only shoots one stream when I think it should go straight to the second. I read about locks and distribution, but don't quite understand. What do I need to do here to allow two threads to work independently at the same time?

import thread def myproc(item): print("Thread fired for " + item) while True: pass things = ['thingone', 'thingtwo'] for thing in things: try: thread.start_new_thread(myproc(thing)) except: print("Error") 
+7
python
source share
2 answers

You have a signature start_new_thread . You call myproc and pass the result as an argument to start_new_thread , which never happens since myproc never ends.

Instead, it should be:

 thread.start_new_thread(myproc, (thing,) ) 

The first argument is a function (i.e., the function object that does not call the function), and the second is a tuple of arguments.

See: https://docs.python.org/2/library/thread.html#thread.start_new_thread

Once your program starts both threads, you probably want to add a pause at the end, because the threads will stop when the main thread ends.

Also, consider using the threading module instead of the thread module, as it provides a much more convenient higher-level interface, such as a convenient way to wait until your threads complete.

See: https://docs.python.org/2/library/threading.html#module-threading

+5
source share

Your application shuts down before the second thread has finished, what can I say.

You need to wait for both of your threads to complete before your application terminates, for example:

 #!/usr/bin/python import thread import time # Define a function for the thread def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: # This is a bad solution due to the busy wait loop. More below. pass 

You should better save the thread objects and use thread1.join() and thread2.join() at the end before exiting to let them know that both of them are complete.

+2
source share

All Articles