2015-09-22 55 views
0

您好我想在這裏運行兩個線程function1function2。我什麼function1先運行,而function1暫停在time.sleep(1000)。我專家function2立即開始與function1一起,並繼續其功能。並行線程無需等待python中的其他線程

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 

回答

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