Python sleep()函數用法:線程睡眠


位於 time 模塊中的 sleep(secs) 函數,可以實現令當前執行的線程暫停 secs 秒后再繼續執行。所謂暫停,即令當前線程進入阻塞狀態,當達到 sleep() 函數規定的時間后,再由阻塞狀態轉為就緒狀態,等待 CPU 調度。

sleep() 函數位於 time 模塊中,因此在使用前,需先引入 time 模塊。

sleep() 函數的語法規則如下所示:

time.sleep(secs)

其中,secs 參數用於指定暫停的秒數,

仍以前面章節創建的 thread 線程為例,下面程序演示了 sleep() 函數的用法:

 1 import threading
 2 import time
 3 #定義線程要調用的方法,*add可接收多個以非關鍵字方式傳入的參數
 4 def action(*add):
 5     for arc in add:
 6         #暫停 0.1 秒后,再執行
 7         time.sleep(0.1)
 8         #調用 getName() 方法獲取當前執行該程序的線程名
 9         print(threading.current_thread().getName() +" "+ arc)
10 #定義為線程方法傳入的參數
11 my_tuple = ("http://c.biancheng.net/python/",\
12             "http://c.biancheng.net/shell/",\
13             "http://c.biancheng.net/java/")
14 #創建線程
15 thread = threading.Thread(target = action,args =my_tuple)
16 #啟動線程
17 thread.start()
18 #主線程執行如下語句
19 for i in range(5):
20     print(threading.current_thread().getName())

程序執行結果為:

MainThread
MainThread
MainThread
MainThread
MainThread
Thread-1 http://c.biancheng.net/python/
Thread-1 http://c.biancheng.net/shell/
Thread-1 http://c.biancheng.net/java/

 

可以看到,和未使用 sleep() 函數的輸出結果相比,顯然主線程 MainThread 在前期獲得 CPU 資源的次數更多,因為 Thread-1 線程中調用了 sleep() 函數,在一定程序上會阻礙該線程獲得 CPU 調度。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM