Python question on threads
I am trying to run two thread concurrently on two function like the ones listed below :
import threading
def functionA():
for i in range(5):
print "Calling function A"
def functionB():
for i in range(5):
print "Calling function B"
t1 = threading.Thread(functionA())
t2 = threading.Thread(functionB())
t1.start()
t2.start()
Results :
Calling function A Calling function A Calling function A Calling function A Calling function A Calling function B Calling function B Calling function B Calling function B Calling functi开发者_如何学Goon B
But unfortunately after trying out several times. I am not able to get the result
The Desired results :
Calling function A Calling function B Calling function A Calling function B Calling function A Calling function B Calling function A Calling function B Calling function A
Can someone guide me so that the two threads can run concurrently at the same time and produce the desired results. Thanks in advance.
You're calling the functions and pass the result to the Thread
constructor instead of passing the function. Also, you must use the target
argument (instead of the unused group
which comes first). Just use Thread(target=functionA)
and Thread(target=functionB)
. Note the lack of parens after the functions.
Note that you still won't get multithreading in CPython, but that's a different question.
@delnan already answered how to use Thread correctly, so I'm going to focus on what you want the desired output to be.
You will most likely NOT be able to get the desired output that you want. The timing of when threads execute is not guaranteed, especially in Python. The OS scheduling can impact when each thread gets to run. When running two threads like this, you're effectively saying "these two pieces of work do not depend on the order of each other and can be run at the same time".
You could get output like this:
a,a,b,b,a,a,b,b,a,b
Or:
a,b,b,b,b,b,a,a,a,a
It will change on every execution of your program. Do NOT rely on the order of thread execution!
Threading in Python is a dangerous beast. No two threads are ever running within Python at exactly the same time. Read up on the Global Interpret Lock for more information.
You are writing a new thread, the operating system takes care of how threads use the processor. That's why the sorting isn't regular. You should use another varible to define which function has turn. But still a bad idea.
It will be great if python 3.2 is release as looking at the link below there are built in libraries that can help me achieve my goals.
http://docs.python.org/dev/library/concurrent.futures.html
But nevertheless will look into the alternative provided by other helpful memebers. Thanks for the help provided once again.
精彩评论