Threading error: AttributeError: 'NoneType' object has no attribute '_initialized'

Threading error: AttributeError: 'NoneType' object has no attribute '_initialized'

我正在尝试学习 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 时,它 returns 错误:

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

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

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

谢谢大家!

您完全错误地使用了 Thread。首先,您没有调用 Thread 构造函数(即您的代码 必须 具有 threading.Thread(<something>) 来创建新的Thread 个实例)。其次,您在 main 线程中使用参数调用 myfunction,而不是在新线程中。第三,该函数的 return 值(隐式 None)作为隐式 self 参数传递给未绑定的 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.