您好我正在尝试在function1
和function2
运行两个主题。我function1
首先运行function1
而time.sleep(1000)
暂停function2
。我专家function1
立即与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
一起开始并继续运行。
Thread-1: Tue Sep 22 19:10:03 2015
返回
git branch-today new_branch_name
答案 0 :(得分:0)
你永远不会得到这种性质的真正确定性调度,但我认为这里的主要问题可能是当主线程出现时
while True:
pass
它处于繁忙的等待状态,在此期间它将占用几乎所有可用的CPU。在Python中,即使您的计算机上有多个核心,您也只会看到一次运行一个(非IO阻塞的)线程。
如果要启动一个或多个线程然后等待它们完成,最简单的方法是使用higher-level threading interface:
from threading import Thread
t = Thread(target=function1, args=("Thread-1", 2))
# ...
t.join() # wait for thread to exit
所有这一切,你的代码似乎表现得像你在我的机器上所期望的那样:
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