线程错误:AttributeError:'NoneType'对象没有属性'_initialized'

时间:2017-06-26 14:34:30

标签: python multithreading python-3.x python-multithreading

我正在尝试了解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'

永远不会执行第二次线程调用。

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

谢谢大家!

1 个答案:

答案 0 :(得分:4)

您完全错误地使用Thread。首先,您没有调用 Thread 构造函数(即您的代码必须 threading.Thread(<something>)才能创建新的Thread实例)。其次,您在 main 线程中使用参数调用myfunction,而不是在新线程中调用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.

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

{{1}}