Python 多執行緒之執行緒本地資料

2021-10-19 23:50:24 字數 2667 閱讀 9255

建立乙個執行緒本地物件

import threading

# 建立執行緒本地物件

current_thread_data = threading.local(

)# 為執行緒本地物件新增屬性

current_thread_data.color =

"blue"

# 直接操作執行緒本地物件的屬性字典

current_thread_data.__dict__.setdefault(

"widgets",[

])# 檢視本地執行緒的資料字典

print

(current_thread_data.__dict__)

輸出:

訪問執行緒本地物件所有執行緒的資料

import threading

log =

deff()

: mydata.number =

1# 記錄當前執行緒的資料

mydata = threading.local(

)thread = threading.thread(target=f)

thread.start(

)thread.join(

)print

(log)

輸出:[1,

]

定製乙個執行緒本地物件

import threading

deff()

:print

(mydata.color)

print

(mydata.number)

mydata.color =

"green"

print

(mydata.__dict__)

class

mylocal

(threading.local)

:# 定義執行緒共享屬性 子類中定義的類屬性可以被所有執行緒共享

number =

1def

__init__

(self,/,

**kw)

:# 定義所有本地執行緒物件的預設值屬性

self.__dict__.update(kw)

defsquare

(self)

:return self.number **

2mydata = mylocal(color=

"red"

)thread = threading.thread(target=f)

print

(mydata.color)

print

(mydata.number)

thread.start(

)thread.join(

)print

(mydata.__dict__)

輸出:red

1red

1

例子

import threading

import time

deftask1()

: current_thread_data.name =

"task1"

while

true

: time.sleep(

0.5)

print

(threading.current_thread(

), current_thread_data.name)

deftask2()

: current_thread_data.name =

"task2"

while

true

: time.sleep(1)

print

(threading.current_thread(

), current_thread_data.name)

if __name__ ==

'__main__'

: current_thread_data = threading.local(

) threading.thread(target=task1)

.start(

) threading.thread(target=task2)

.start(

)

輸出:1, started 23808

)> task1

2, started 25580

)> task2

1, started 23808

)> task1

1, started 23808

)> task1

2, started 25580

)> task2

1, started 23808

)> task1

1, started 23808

)> task1

2, started 25580

)> task2

1, started 23808

)> task1

1, started 23808

)> task1..

....

python多執行緒之動態確定執行緒數

1 2 建立執行緒,也可以動態確定執行緒數 3 4 encoding utf 856 7import threading 8import time 9import random 1011 12def print time thread name,step 13 python的time.ctime 函...

Python多執行緒之event

事件 event 用於執行緒間同步和通訊。比如執行緒a要完成某一任務 event 執行緒b才能執行後面的 怎麼實現呢,就是用event。event常用方法 釋義set 開始乙個事件 wait 如果未設定set狀態會一直等待,否則過 clear 清除set狀態 isset 是否設定set狀態 注意 w...

Python多執行緒之threading

1.多執行緒的基礎函式及增加執行緒add thread import threading 1.基礎函式 def main print threading.active count 列印目前程序的數目 print threading.enumerate 檢視程序列表 print threading.c...