Python多線程編程初體驗
前言
這將是一個系列,一個關(guān)于進程、線程和 協(xié)程的系列。
主要用于:回顧和復(fù)習(xí)以往所學(xué)的知識 以及 希望這點經(jīng)驗?zāi)軌驇椭趯W(xué)習(xí)編程的你
查看線程ID
創(chuàng)建文件 0809.py
- import time
- import threading
- def loop():
- while True:
- print('thread id is {}'.format(threading.get_native_id()))
- time.sleep(3)
- if __name__ == '__main__':
- loop()
在第一個終端窗口中執(zhí)行
- $ python 0809.py
- thread id is 3344
- thread id is 3344
- thread id is 3344
- ······
在第二個終端窗口中執(zhí)行
- ps -ef | grep 'python 0809.py'
- vagrant 3344 3117 0 16:26 pts/1 00:00:00 python 0809.py
- 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ī)定,當(dāng)一個進程中只有一個線程的情況下,線程ID等于進程ID?;騽t說,進程的第一個線程(主線程)的ID等于進程ID。
經(jīng)典的生產(chǎn)者/消費者模型(也有人稱之為,發(fā)布/訂閱模型)
- # 0809.py
- import time
- import threading
- count = 0
- def consumer():
- global count
- while True:
- if count <= 0:
- continue
- count = count - 1
- print(f'count is {count}, consumer thread id is {threading.get_native_id()}')
- time.sleep(2)
- def producer():
- global count
- while True:
- count = count + 1
- print(f'count is {count}, producer thread id is {threading.get_native_id()}')
- time.sleep(1)
- if __name__ == '__main__':
- tp = threading.Thread(target=producer)
- tc = threading.Thread(target=consumer)
- tp.start()
- tc.start()
執(zhí)行命令 python 0809.py
- $ python 0809.py
- count is 1, producer thread id is 3785
- count is 0, consumer thread id is 3786
- count is 1, producer thread id is 3785
- count is 0, consumer thread id is 3786
- count is 1, producer thread id is 3785
- count is 2, producer thread id is 3785
- count is 1, consumer thread id is 3786
- count is 2, producer thread id is 3785
可以發(fā)現(xiàn),兩個線程并非嚴格交替執(zhí)行,而是隨機執(zhí)行。
我們再來查看一下相關(guān)的進程和線程
- $ ps -ef | grep 'python 0809.py'
- vagrant 3784 3117 0 17:24 pts/1 00:00:00 python 0809.py
- vagrant 3789 3451 0 17:24 pts/0 00:00:00 grep --color=auto python 0809.py
- $ ps -T -p 3784
- PID SPID TTY TIME CMD
- 3784 3784 pts/1 00:00:00 python
- 3784 3785 pts/1 00:00:00 python
- 3784 3786 pts/1 00:00:00 python
可以看出該進程中有三個線程,分別是主線程 3784 和兩個子線程 3785(producer)、3786(consumer)
今天我們就先講到這里,重點掌握:
1、如何在python代碼中和shell終端中查看線程id 進程ID 以及進程中包含的線程。
2、理解生產(chǎn)/消費者模型,因為這個模型會在接下來的學(xué)習(xí)中被多次提到