gpt4 book ai didi

python - 线程错误 : AttributeError: 'NoneType' object has no attribute '_initialized'

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:43 26 4
gpt4 key购买 nike

我正在尝试学习 Python 3 上的线程。我做了一个示例代码:

import time 
import threading

def myfunction(string,sleeptime,lock,*args):
count = 0
while count < 2:
#entering critical section
lock.acquire()
print(string, " Now sleeping after Lock acquired for ",sleeptime)
time.sleep(sleeptime)
print(string, " Now releasing lock and sleeping again.\n",time.ctime(time.time()))
lock.release()
#exiting critical section
time.sleep(sleeptime)
count+=1
#threading.Thread.daemon=True

if __name__!="__main__":
lock = threading.Lock()
try:
threading.Thread.start(myfunction("Thread Nº 1",2,lock))
threading.Thread.start(myfunction("Thread Nº 2",2,lock))
except:
raise

while 1:pass

它部分起作用。当它到达 while<2 loop ,它返回错误:

Traceback (most recent call last):
File "python", line 22, in <module>
AttributeError: 'NoneType' object has no attribute '_initialized'

并且从不执​​行第二个线程调用。

我该怎么做才能纠正这个问题?

谢谢大家!

最佳答案

您正在使用 Thread完全错误。首先,您没有调用 Thread 构造函数(即你的代码必须threading.Thread(<something>) 来创建新的 Thread 实例)。其次,您正在调用 myfunctionmain 线程中使用参数,而不是在新线程中。第三,该函数的返回值(隐式 None )作为隐式 self 传递。未绑定(bind)的参数 Thread.start方法!

正确的做法是

t1 = threading.Thread(target=myfunction, args=("Thread Nº 1", 2, lock))
t1.start()

同样适用于 t2 .此外,如果您这样做,您将保留对 Thread 的引用。对象,您可以替换 while 1: pass

t1.join()
t2.join()
print("Both threads exited, exiting.")

或者同样地:

for t in [t1, t2]:
t.join()
print("Both threads exited, exiting.")

经过这些修改,程序将输出

Thread Nº 1  Now sleeping after Lock acquired for  2
Thread Nº 1 Now releasing lock and sleeping again.
Mon Jun 26 17:42:32 2017
Thread Nº 2 Now sleeping after Lock acquired for 2
Thread Nº 2 Now releasing lock and sleeping again.
Mon Jun 26 17:42:34 2017
Thread Nº 1 Now sleeping after Lock acquired for 2
Thread Nº 1 Now releasing lock and sleeping again.
Mon Jun 26 17:42:36 2017
Thread Nº 2 Now sleeping after Lock acquired for 2
Thread Nº 2 Now releasing lock and sleeping again.
Mon Jun 26 17:42:38 2017
Both threads exited, exiting.

关于python - 线程错误 : AttributeError: 'NoneType' object has no attribute '_initialized' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com