请注意以下代码(Win10上的python3.6,PyCharm),函数thread0(self)
作为线程成功启动,但是thread1(self)
似乎与thread0(self)
的设置方式不同。self.thread0
可以,但self.thread1
不行。self.thread1
中的self
在它的类函数中没有thread1
,但是它有__init__()
中的所有内容。事实上,在PyCharm中,参数self
甚至没有在def thread1(self):
行中突出显示。我的理解是,像foo(self)
这样的语法会将foo()添加为self
所指类的成员。你知道吗
既然我们在这里,我就无法解释为什么启动thread0的try-catch块中的代码也失败了,可能与线程的特定语法要求有关?你知道吗
我有一种感觉,像这样嵌套使用self
可能是不推荐的。但在我的实际代码中,我确实需要线程声明位于新进程中而不是main()
,这样这些线程就可以共享该进程的同一个python记录器。你知道吗
import threading
import multiprocessing
from time import sleep
class exe0(multiprocessing.Process):
def __init__(self):
super().__init__()
self.aaa = 111
# working syntax for thread0
t = threading.Thread(
target=self.thread0,
daemon=1,
)
t.start()
try:
# NOT working syntax
t = threading.Thread(
target=thread0,
args=(self,),
daemon=1,
)
t.start()
sleep(1)
except Exception as e:
print(e)
def thread0(self):
print(type(self))
def run(self):
# working syntax for thread1
def thread1(self):
print(type(self))
print(self.aaa)
t = threading.Thread(
target=thread1,
args=(self,),
daemon=1,
)
t.start()
sleep(1)
try:
# NOT working syntax
t = threading.Thread(
target=self.thread1,
daemon=1,
)
t.start()
sleep(1)
except Exception as e:
print(e)
if __name__ == '__main__':
multiprocessing.freeze_support()
e = exe0()
e.daemon = 1
e.start()
sleep(2)
# output:
'''
<class '__main__.exe0'>
name 'thread0' is not defined
<class '__mp_main__.exe0'>
111
'exe0' object has no attribute 'thread1'
'''
您忘了理解self是jussst变量名,表示什么是另一回事,要使代码正常工作,您只需为变量选择另一个名称,请看:
您忘记了在名为
t4
的线程中以方法为目标现在您得到了6个输出,例如:
相关问题 更多 >
编程相关推荐