av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

Python多線程編程初體驗

 前言

這將是一個系列,一個關(guān)于進程、線程和 協(xié)程的系列。

主要用于:回顧和復(fù)習以往所學的知識 以及 希望這點經(jīng)驗?zāi)軌驇椭趯W習編程的你

查看線程ID

創(chuàng)建文件 0809.py

 
 
 
  1. import time 
  2. import threading 
  3.  
  4. def loop(): 
  5.     while True: 
  6.         print('thread id is {}'.format(threading.get_native_id())) 
  7.         time.sleep(3) 
  8.          
  9. if __name__ == '__main__': 
  10.     loop() 

在第一個終端窗口中執(zhí)行

 
 
 
  1. $ python 0809.py  
  2. thread id is 3344 
  3. thread id is 3344 
  4. thread id is 3344 
  5. ······ 

在第二個終端窗口中執(zhí)行

 
 
 
  1. ps -ef | grep 'python 0809.py' 
  2. vagrant   3344  3117  0 16:26 pts/1    00:00:00 python 0809.py 
  3. vagrant   3662  3451  0 16:30 pts/0    00:00:00 grep --color=auto python 0809.py 

你會發(fā)現(xiàn)其進程ID也是 3344和線程ID一致。這是因為Linux中規(guī)定,當一個進程中只有一個線程的情況下,線程ID等于進程ID。或則說,進程的第一個線程(主線程)的ID等于進程ID。

經(jīng)典的生產(chǎn)者/消費者模型(也有人稱之為,發(fā)布/訂閱模型)

 
 
 
  1. # 0809.py  
  2. import time 
  3. import threading 
  4.  
  5. count = 0 
  6.  
  7. def consumer(): 
  8.     global count 
  9.     while True: 
  10.         if count <= 0: 
  11.             continue 
  12.         count = count - 1 
  13.         print(f'count is {count}, consumer thread id is {threading.get_native_id()}') 
  14.         time.sleep(2) 
  15.  
  16. def producer(): 
  17.     global count 
  18.     while True: 
  19.         count = count + 1 
  20.         print(f'count is {count}, producer thread id is {threading.get_native_id()}') 
  21.         time.sleep(1) 
  22.          
  23. if __name__ == '__main__': 
  24.     tp = threading.Thread(target=producer) 
  25.     tc = threading.Thread(target=consumer) 
  26.     tp.start() 
  27.     tc.start() 

執(zhí)行命令 python 0809.py

 
 
 
  1. $ python 0809.py  
  2. count is 1, producer thread id is 3785 
  3. count is 0, consumer thread id is 3786 
  4. count is 1, producer thread id is 3785 
  5. count is 0, consumer thread id is 3786 
  6. count is 1, producer thread id is 3785 
  7. count is 2, producer thread id is 3785 
  8. count is 1, consumer thread id is 3786 
  9. count is 2, producer thread id is 3785 

可以發(fā)現(xiàn),兩個線程并非嚴格交替執(zhí)行,而是隨機執(zhí)行。

我們再來查看一下相關(guān)的進程和線程

 
 
 
  1. $ ps -ef | grep 'python 0809.py' 
  2. vagrant   3784  3117  0 17:24 pts/1    00:00:00 python 0809.py 
  3. vagrant   3789  3451  0 17:24 pts/0    00:00:00 grep --color=auto python 0809.py 
  4.  
  5. $ ps -T -p 3784 
  6.   PID  SPID TTY          TIME CMD 
  7.  3784  3784 pts/1    00:00:00 python 
  8.  3784  3785 pts/1    00:00:00 python 
  9.  3784  3786 pts/1    00:00:00 python 

可以看出該進程中有三個線程,分別是主線程 3784 和兩個子線程 3785(producer)、3786(consumer)

今天我們就先講到這里,重點掌握:

1、如何在python代碼中和shell終端中查看線程id 進程ID 以及進程中包含的線程。

2、理解生產(chǎn)/消費者模型,因為這個模型會在接下來的學習中被多次提到


網(wǎng)頁名稱:Python多線程編程初體驗
文章位置:http://uogjgqi.cn/article/dhjeioe.html
掃二維碼與項目經(jīng)理溝通

我們在微信上24小時期待你的聲音

解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流