【发布时间】:2016-04-20 08:31:51
【问题描述】:
我对 python 的多线程有一些问题: 生成一个线程,它会获取一些参数,如线程名称、计数器等。在线程的“运行”部分中,它正在调用一些子函数(并且还有一些深度的子函数)但是,自变量(类)似乎不存在于子函数中:指的是 self.name显示一些错误(NameError: global name 'self' is not defined )。有没有办法在不(!!)参数化所有内容的情况下获得这些子函数中完整结构的内容(这将在深度 4 处变得很长......)。希望这个简短的例子能更好地解释它,在 sub1 第二个打印行尝试访问 self.counter
#!/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(self)
标签: python multithreading global-variables