Python3多執行緒並獲取返回值

2022-08-22 11:00:17 字數 2085 閱讀 3547

1

from threading import

thread23

4class

mythread(thread):

5def

__init__(self, func, *params, **kwargs):

6"""

7:param func: object 待執行的函式物件

8:param params: tuple 函式的引數

9:param kwargs: dict 函式的key-value引數

10"""

11 thread.__init__

(self)

12 self.func =func

13 self.args =params

14 self.kwargs =kwargs

15 self.result =none

1617

#呼叫mythread.start()時該函式會自動執行

18def

run(self):

19 self.result = self.func(*self.args, **self.kwargs)

2021

22class

threads(object):

23"""

24併發執行多個執行緒,並獲取程序的返回值

25"""

26def

__init__

(self):

27 self.threads =list()

28 self.result = list() #

程序執行的返回值組成的列表

2930

defadd(self, my_thread):

31"""

32將任務新增到待執行執行緒佇列中

33:param my_thread: mythread 執行緒物件

34:return:

35"""

3637

38def

exec

(self):

39"""

40多執行緒同時執行執行緒佇列中的人物

41:return:

42"""43#

啟動程序序列

44for t in

self.threads:

45t.start()

4647

#等待程序序列執行完成

48for t in

self.threads:

49t.join()

5051

#獲取執行緒返回值

52for t in

self.threads:

5354

5556

if__name__ == "

__main__":

57from time import

sleep

5859

deftest_add(name, a, b, num):

60for i in

range(num):

61 sleep(1)

62print("

{}: {}

".format(name, i))

63return a+b

6465 thread1 = mythread(test_add, "

thread1

", 1, 2, 5)

66 thread2 = mythread(test_add, "

thread2

", a=2, b=3, num=4)

67 threads =threads()

68threads.add(thread1)

69threads.add(thread2)

70 threads.exec

()71

print(threads.result)

Python3多執行緒

學習python執行緒 python3 執行緒中常用的兩個模組為 thread threading 推薦使用 thread 模組已被廢棄。使用者可以使用 threading 模組代替。所以,在 python3 中不能再使用 thread 模組。為了相容性,python3 將 thread 重新命名為...

python3 多執行緒

多執行緒簡介 執行緒 thread 也稱輕量級程序,時作業系統能夠進行運算排程的最小單位,它被包涵在程序之中,時程序中的實際運作單位。執行緒自身不擁有資源,只擁有一些在執行中必不可少的資源,但他可與同屬乙個程序的其他執行緒共享程序所擁有的全部資源。乙個執行緒可以建立和撤銷另乙個執行緒,同一程序中的多...

python3 多執行緒,執行緒鎖

python使用多執行緒,不一定執行速度快,這裡引入gil global interpreter lock python直譯器中任意時刻都只有乙個執行緒在執行 gil執行過程 1 設定乙個gil 2 切換執行緒去準備執行任務 runnale就緒狀態 3 執行 4 可能出現的狀態 執行緒任務執行結束 ...