本週開始暑假就正式結束了,這周由於學校安排的認識實習的緣故並無什麼進度,只學習了部分Python線程相關的東西網絡
首先是單線程的測試,下圖是運行效果圖多線程
代碼以下:dom
1 from time import sleep,ctime 2 def fun1(): 3 print('開始運行fun1:',ctime()) 4 #休眠4s 5 sleep(4) 6 print('fun1運行結束:',ctime()) 7 def fun2(): 8 print('開始運行fun2:',ctime()) 9 # 休眠2s 10 sleep(2) 11 print('fun2運行結束:', ctime()) 12 def main(): 13 print("開始運行時間:",ctime()) 14 #在單線程中調用fun1函數和fun2函數 15 fun1() 16 fun2() 17 print("結束運行時間:",ctime()) 18 if __name__=='__main__': 19 main()
接下來是多線程程序測試,效果圖以下:函數
代碼以下:學習
1 import _thread as thread 2 from time import sleep,ctime 3 def fun1(): 4 print('開始運行fun1:',ctime()) 5 #休眠4s 6 sleep(4) 7 print('fun1運行結束:',ctime()) 8 def fun2(): 9 print('開始運行fun2:',ctime()) 10 #休眠2s 11 sleep(2) 12 print('fun2運行結束:',ctime()) 13 def main(): 14 print('開始運行時間:',ctime()) 15 #啓動一個線程運行fun1函數 16 thread.start_new_thread(fun1(),()) 17 #啓動一個線程運行fun2函數 18 thread.start_new_thread(fun2(),()) 19 #休眠6s 20 sleep(6) 21 print('結束運行時間:',ctime()) 22 if __name__=='__main__': 23 main()
而後是爲線程函數傳遞參數的測試,效果圖以下:測試
代碼以下:ui
1 import random 2 from time import sleep,ctime 3 import _thread as thread 4 #線程函數,其中a和b是經過start_new_thread函數傳入的參數 5 def fun(a,b): 6 print(a,b) 7 # 隨機休眠一段時間(1~4秒) 8 sleep(random.randint(1,4)) 9 #啓動8個線程 10 for i in range(8): 11 # 爲每個線程函數傳入兩個參數值 12 thread.start_new_thread(fun,(i+1,'a'*(i+1))) 13 # 經過從終端輸入一個字符串的方式讓程序暫停 14 input()
接下來是線程和鎖的測試,效果圖以下:spa
代碼以下:線程
1 import _thread as thread 2 from time import sleep,ctime 3 # 線程函數,index是一個整數類型的索引,sec是休眠時間(單位:秒),lock是鎖對象 4 def fun(index,sec,lock): 5 print('開始執行',index,'執行時間',ctime()) 6 #休眠 7 sleep(sec) 8 print('執行結束',index,'執行時間',ctime()) 9 # 釋放鎖對象 10 lock.release() 11 def main(): 12 # 建立第一個鎖對象 13 lock1=thread.allocate_lock() 14 # 獲取鎖,至關於把鎖鎖上 15 lock1.acquire() 16 # 啓動第一個線程,並傳入第一個鎖對象,10是索引,4是休眠時間,lock1是鎖對象 17 thread.start_new_thread(fun,(10,4,lock1)) 18 # 建立第二個鎖對象 19 lock2 = thread.allocate_lock() 20 # 獲取鎖,至關於把鎖鎖上 21 lock2.acquire() 22 # 啓動第二個線程,並傳入第一個鎖對象,10是索引,4是休眠時間,lock1是鎖對象 23 thread.start_new_thread(fun, (20, 2, lock2)) 24 # 使用while循環和locked方法判斷lock1和lock2是否被釋放 25 while lock1.locked() or lock2.locked(): 26 pass 27 if __name__=='__main__': 28 main()
以上就是本週全部內容了,下週將繼續U-NET神經網絡的學習和實踐,加油!!!3d