Sno*_*wBG 1 python multithreading python-multithreading python-3.x
我正在尝试了解 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
Run Code Online (Sandbox Code Playgroud)
它部分起作用。当它到达 时while<2 loop,它返回错误:
Traceback (most recent call last):
File "python", line 22, in <module>
AttributeError: 'NoneType' object has no attribute '_initialized'
Run Code Online (Sandbox Code Playgroud)
并且从不执行第二个线程调用。
我能做些什么来纠正这个问题?
谢谢你们!
您使用的Thread完全不正确。首先,你不调用Thread构造函数(即你的代码必须具有threading.Thread(<something>)创建新Thread实例)。其次,您myfunction在主线程中调用with 参数,而不是在新线程中。第三,该函数的返回值(隐式None)作为隐式self参数传递给未绑定的Thread.start方法!
正确的做法是
t1 = threading.Thread(target=myfunction, args=("Thread Nº 1", 2, lock))
t1.start()
Run Code Online (Sandbox Code Playgroud)
同样对于t2. 此外,如果你像这样做,你将保留引用Thread对象,并且可以更换while 1: pass用
t1.join()
t2.join()
print("Both threads exited, exiting.")
Run Code Online (Sandbox Code Playgroud)
或者同样:
for t in [t1, t2]:
t.join()
print("Both threads exited, exiting.")
Run Code Online (Sandbox Code Playgroud)
通过这些修改,程序将输出
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6184 次 |
| 最近记录: |