我有一些python的多線程問題: 生成一個線程,它獲取一些參數,如線程名稱,計數器等。在線程的「運行」部分,它調用了一些子函數(並且在那裏還有一些子函數)。但是,自變量(類)似乎不存在於子函數中:引用self.name顯示出一些錯誤(NameError:全局名稱'self'未定義爲 )。沒有任何方法可以在沒有(!!)參數化所有內容的情況下獲取這些子函數中的完整結構的內容(這將在深度4時變得很長)。希望這個簡短的例子會更好地解釋它,在SUB1第二打印線試圖訪問self.counterpython:multithreading:self作爲全局變量
#!/usr/bin/python
import threading
import time
globalVar = 1;
def sub1 (name):
global globalVar ;
print str(globalVar) + " in der 1. subfunktion von " +str(name)
print "teste self" + str(self.counter) + " - " + globalVar + " " +str(name) ;
globalVar += 1 ;
time.sleep(1);
sub2 (name) ;
return None ;
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name + " mit zaehler " + str(self.counter)
sub1 (self.name);
threadLock = threading.Lock()
threads = [] ;
# Create new threads
count =0;
while count < 10 :
count += 1;
threadX = myThread(count, "Thread-" + str(count), count)
threadX.start()
threads.append(threadX)
for t in threads:
t.join()
print "Exiting Main Thread"
感謝您的幫助
你有沒有嘗試在線程運行中傳遞整個對象'self'而不是隻有一個屬性'self.name'? 'SUB1(個體)' –