Reputation: 2352
Hi I am trying to run two threads here function1
and function2
. I what function1
to run first and while function1
is paused at time.sleep(1000)
.I expert function2
to start immediately along with function1
and continue it function.
import thread
import time
# Define a function for the thread
def function1( threadName, delay):
print "%s: %s" % ( threadName, time.ctime(time.time()) )
time.sleep(1000)
def function2( 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( function1, ("Thread-1", 2, ) )
thread.start_new_thread( function2, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while True:
pass
Return
Thread-1: Tue Sep 22 19:10:03 2015
Upvotes: 0
Views: 1192
Reputation: 12879
You're never going to get truly deterministic scheduling of this nature, but I think the main problem here is probably that when the main thread does
while True:
pass
it is in a busy wait state, during which it will take virtually all of the available CPU. In Python, even if you have multiple cores on your machine, you'll only see one (non-IO-blocked) thread running at a time.
If you want to launch one or more threads and then wait for them to finish, it's probably easiest to use the higher-level threading interface:
from threading import Thread
t = Thread(target=function1, args=("Thread-1", 2))
# ...
t.join() # wait for thread to exit
All that being said, your code seems to behave as you are expecting it to on my machine:
C:\Python27\python.exe C:/dev/python/scratch/concurrent.py
Thread-1: Tue Sep 22 13:37:51 2015
Thread-2: Tue Sep 22 13:37:55 2015
Thread-2: Tue Sep 22 13:37:59 2015
Thread-2: Tue Sep 22 13:38:03 2015
Thread-2: Tue Sep 22 13:38:07 2015
Thread-2: Tue Sep 22 13:38:11 2015
Upvotes: 1