簡體   English   中英

Python線程 - 多線程崩潰

[英]Python Threading - Crash with multiple threads

我使用Python的線程模塊編寫了一個用於多線程的小python腳本。
threading.Thread調用的目標函數需要2個參數( self和另一個值)。 但是我總是得到以下錯誤TypeError: example() takes 2 positional arguments but 3 were given即使只TypeError: example() takes 2 positional arguments but 3 were given了2個參數,也會給出TypeError: example() takes 2 positional arguments but 3 were given個參數。

import threading
import random
num=random.randint(1,999)

threadN=10 #number of processes
a="11" #testing value
class ExampleClass():
    def __init__(self):
        self.num=num

    def example(self,a):
        print(self.num)
        print(a)

if __name__ == '__main__':
    cl=ExampleClass()
    while threadN>0:

        threading.Thread(target=cl.example, args=(a)).start()
        threadN-=1

任何幫助,將不勝感激!

args必須是list或tuple但()不會創建元組。 你必須使用逗號來創建單值的元組 - args=(a,)

 threading.Thread(target=cl.example, args=(t,)).start()

()這里只是單獨的逗號,它用逗號創建元組,它在函數中分隔參數。 你可以在沒有()情況下做同樣的事情,但你必須在線程之前創建元組

 arguments = a,
 threading.Thread(target=cl.example, args=arguments).start()

好的,剛剛發現我的問題,再次查看文檔並發現以下內容:

threading.Thread(target=cl.example args=[t]).start()使用[]作為參數解決問題...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM