Python多線程如何使用全局ThreadLocal對(duì)象
在編寫Python多線程程序時(shí),我們經(jīng)常會(huì)遇到不同線程的局部變量需要傳遞的問題。為了解決這個(gè)問題,Python引入了ThreadLocal對(duì)象。本文將通過一個(gè)案例來演示如何使用全局ThreadLoca
在編寫Python多線程程序時(shí),我們經(jīng)常會(huì)遇到不同線程的局部變量需要傳遞的問題。為了解決這個(gè)問題,Python引入了ThreadLocal對(duì)象。本文將通過一個(gè)案例來演示如何使用全局ThreadLocal對(duì)象。
案例環(huán)境準(zhǔn)備
首先,我們需要在一臺(tái)Ubuntu虛擬機(jī)上進(jìn)行實(shí)驗(yàn)。打開VMware虛擬化軟件,并啟動(dòng)Ubuntu虛擬機(jī)。登錄系統(tǒng)后,在桌面空白處右鍵鼠標(biāo),選擇“打開終端”。
創(chuàng)建并編輯代碼文件
在終端中使用gedit編輯器創(chuàng)建一個(gè)名為的文件,命令如下:
```
gedit
```
在文件中,編寫以下代碼:
```python
from threading import Thread
class Student:
def __init__(self, name):
name
def pro_func(self, name):
std Student(name)
self.task1(std)
self.task2(std)
def task1(self, std):
print('我是task1:', )
def task2(self, std):
print('我是task2:', )
t1 Thread(target_func, args('denny',))
t2 Thread(target_func, args('andy',))
()
()
()
()
```
運(yùn)行代碼并觀察結(jié)果
在終端中運(yùn)行以下命令執(zhí)行代碼:
```
python3
```
結(jié)果如下圖所示,每個(gè)線程都打印出了兩次。這種方法在函數(shù)之間傳遞參數(shù)比較麻煩。
使用全局字典解決傳參問題
為了避免傳遞參數(shù)的麻煩,我們可以使用全局字典的方法來解決。修改代碼如下:
```python
from threading import Thread, current_thread
class Student:
def __init__(self, name):
name
global_dict {}
def pro_func(name):
std Student(name)
global_dict[current_thread()] std
task1()
task2()
def task1():
std global_dict[current_thread()]
print('我是task1:', )
def task2():
std global_dict[current_thread()]
print('我是task2:', )
t1 Thread(targetpro_func, args('denny',))
t2 Thread(targetpro_func, args('andy',))
()
()
()
()
```
再次運(yùn)行代碼并觀察結(jié)果
在終端中運(yùn)行以下命令執(zhí)行代碼:
```
python3
```
結(jié)果如下圖所示,盡管沒有傳遞變量的問題了,但是每個(gè)線程依然不能單獨(dú)處理不同的Student對(duì)象。
使用ThreadLocal對(duì)象解決問題
為了實(shí)現(xiàn)單獨(dú)處理不同的Student對(duì)象的功能,我們可以使用ThreadLocal對(duì)象。修改代碼如下:
```python
from threading import Thread, current_thread, local
localstd local()
def pro_func(name):
name
task()
def task():
print('我是task:', )
t1 Thread(targetpro_func, args('denny',))
t2 Thread(targetpro_func, args('andy',))
()
()
()
()
```
再次運(yùn)行代碼并觀察結(jié)果
在終端中運(yùn)行以下命令執(zhí)行代碼:
```
python3
```
結(jié)果如下圖所示,對(duì)于每個(gè)線程而言,都是線程的局部變量,實(shí)現(xiàn)了單獨(dú)處理不同的Student對(duì)象的功能。