日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python3 线程隔离_Python的线程隔离实现方法

發布時間:2023/12/2 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3 线程隔离_Python的线程隔离实现方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前段時間看了下flask的源碼,對于這樣一個輕量級的web框架是怎樣支持多線程的感到非常好奇,于是深入了解了一番。

flask是依賴werkeug來實現線程間的隔離的,而werkeug最后又使用到了python的內置模塊locals來承載數據,看不如寫,于是自己實現了一下。

from threading importcurrentThread, Threadfrom collections importdefaultdictimportsysclassLocalProxy(object):def __init__(self):

self.local=defaultdict(dict)def __repr__(self):returnstr(self.local)def __str__(self):returnstr(self.local)def __getitem__(self, item):returnself.local[currentThread().ident][item]def __setitem__(self, key, value):

self.local[currentThread().ident].update({key: value})print(sys.version)

local_proxy=LocalProxy()print(local_proxy)

local_proxy["main"] = "start"

defchange_property():

local_proxy["main"] = "end"change_thread= Thread(target=change_property)

change_thread.daemon=True

change_thread.start()

change_thread.join()print(local_proxy)

輸出:

3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64bit (AMD64)]

defaultdict(, {})

defaultdict(, {7092: {‘main‘: ‘start‘}, 4892: {‘main‘: ‘end‘}})

這里是使用locals來作為數據承載的dict,然后使用currentThread方法獲取當前線程id,以此作為key來實現各線程間的數據隔離。

從輸出可以看出,主線程設置了`main=start`后,子線程對該屬性進行修改并未成功,而是在自己的線程id下創建了新的屬性。

實現過程中還發生了一個小插曲,當時的開啟線程代碼如下:

change_thread =Thread(change_property)

change_thread.daemon=True

change_thread.start()

報錯:

Traceback (most recent call last):3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64bit (AMD64)]

defaultdict(, {})

File"E:/project/blog/blog/src/utils/local_.py", line 34, in change_thread=Thread(change_property)

File"D:UsersAdministratorAnaconda3libhreading.py", line 781, in __init__

assert group is None, "group argument must be None for now"AssertionError: group argument must be Nonefor now

于是點開Thread源碼看看這個group為何物:

def __init__(self, group=None, target=None, name=None,

args=(), kwargs=None, *, daemon=None):"""This constructor should always be called with keyword arguments. Arguments are:

*group* should be None; reserved for future extension when a ThreadGroup

class is implemented.

原來Thread的初始化增加了group參數,切對其進行了斷言,為以后即將實現的ThreadGroup鋪路。

ps:?以后傳參還是盡量帶上參數名。

Python的線程隔離實現方法

總結

以上是生活随笔為你收集整理的python3 线程隔离_Python的线程隔离实现方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。