[英]Run threads simultaneously in python
所以,我試圖同時運行 2 個線程。 我的代碼如下所示:
from threading import Thread
def Main():
n = 10
k = 2
max = n//k
def firstfunc():
for i in range(0, max):
print(i)
def secondfunc():
for i in range(0, max):
print(i+10)
if __name__ == '__main__':
T1 = Thread(target=Main().firstfunc, args=()).start
T2 = Thread(target=Main().secondfunc, args=()).start
for thread in [T1, T2]:
thread.join()
拋出的錯誤:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [2], line 14
11 print(i+10)
13 if __name__ == '__main__':
---> 14 T1 = Thread(target=Main().firstfunc, args=()).start
15 T2 = Thread(target=Main().secondfunc, args=()).start
16 for thread in [T1, T2]:
AttributeError: 'NoneType' object has no attribute 'firstfunc'
我在網上搜索並咨詢了 stackoverflow 對類似問題的回答,但對我沒有任何幫助。 有誰知道我做錯了什么?
Main()
返回None
因為您沒有在代碼中返回任何內容。 因此Main().firstfunc
就像None.firstfunc
一樣是一個錯誤,因為'NoneType' object has no attribute 'firstfunc'
。
一般來說,無法訪問函數的局部變量( n, k, max, firstfunc, secondfunc
是Main
的局部變量),它們不會自動成為 function 或其返回值的屬性。
您可以自己返回函數:
def Main():
n = 10
k = 2
max = n//k
def firstfunc():
for i in range(0, max):
print(i)
def secondfunc():
for i in range(0, max):
print(i+10)
return firstfunc, secondfunc
if __name__ == '__main__':
first, second = Main()
T1 = Thread(target=first, args=())
T2 = Thread(target=second, args=())
for thread in (T1, T2):
thread.start() # CALL the `start` method!
for thread in [T1, T2]:
thread.join()
示例 output:
0
1
10
2
3
4
11
12
13
14
錯誤說是因為 Main function 返回 None 和 None 沒有屬性 firstfunc 等等。
我的建議只是像這樣更改為 class :
from threading import Thread
class MyClass:
n = 10
k = 2
border = n//k
def firstfunc(a):
global border
for i in range(MyClass.border):
print(i)
def secondfunc(b):
for i in range(MyClass.border):
print(i+10)
if __name__ == '__main__':
T1 = Thread(target=MyClass().firstfunc, args=())
T1.start()
T2 = Thread(target=MyClass().secondfunc, args=())
T2.start()
for thread in [T1, T2]:
thread.join()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.