Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.locked()即使在python多线程环境中调用release()后也返回True_Python_Multithreading_Python Multithreading - Fatal编程技术网

.locked()即使在python多线程环境中调用release()后也返回True

.locked()即使在python多线程环境中调用release()后也返回True,python,multithreading,python-multithreading,Python,Multithreading,Python Multithreading,我试图用python线程编写我的第一个代码 请看代码 当我使用release释放线程的锁时,会出现一个问题,因为它表示锁仍然可用[locked在释放后返回True] import threading import time class thread (threading.Thread): def __init__(self,t,d,arr,lock): threading.Thread.__init__(self) self.name=t

我试图用python线程编写我的第一个代码

请看代码 当我使用release释放线程的锁时,会出现一个问题,因为它表示锁仍然可用[locked在释放后返回True]

import threading
import time

class thread (threading.Thread):
    def __init__(self,t,d,arr,lock):
        threading.Thread.__init__(self)
        self.name=t
        self.delay=d
        self.array=arr;
        self.lock=lock
    def run(self):
       self.fun1()


   def fun1(self):
       print "the thread %s want to take a lock now" %self.name
       self.lock.acquire()
       print "lock status just after lock acquire    foe",self.name,self.lock.locked()

       time.sleep(self.delay)

       print "release lock for %s" %self.name
       self.lock.release()
       time.sleep(2)
       print "lock status after lock release is",self.name,self.lock.locked()
 lck=threading.Lock()
 obj1=thread('T1',5,[1,2,3],lck)
 obj2=thread('T2',10,[4,5,6],lck)


 obj1.start()
 obj2.start()
输出

=====
    the thread T1 want to take a lock now
the thread T2 want to take a lock now

lock status just after lock acquire foe T2 True
release lock for T2
lock status just after lock acquire foe T1 True
lock status after lock release is T2 True
release lock for T1
lock status after lock release is T1 False
我的问题是:

线程T2首先获得锁并执行其空格。 我们可以使用查看T2的锁定状态。锁定是紧随其后的锁定状态

锁定获取目标T2为真。所以T2现在有锁了。 一旦T2使用release释放了锁,那么T1也按预期获得了锁

但是在使用release释放T2的锁后,locked表示True。这意味着T2仍然可用锁?在这种情况下,T1是如何获得锁的?。一旦T1被执行并且在释放之后,我可以看到.locked返回False。对于T1来说,锁定的设备按预期工作,因为一旦释放锁定,它立即返回False

简而言之, 为什么我的第一个线程T2在锁释放后仍然返回True?
如果我只执行一个线程,它将按预期工作。

当您将锁对象传递给构造函数时,它不会被复制,因此每个线程对象都可以访问同一个锁

这导致self.lock.locked返回True,因为锁仍然被锁定,但这次它已被另一个线程锁定

这就是实际发生的情况:

>>> import threading
>>> lck = threading.Lock() # the 'original'
>>> lck2 = lck # lck2 isn't a copy of lck!
>>> lck.acquire()
True
>>> lck2.locked() # lck2 has been acquired as well as lck 
True
>>> lck2.release()
>>> lck.locked() # lck has been released as well as lck2
False
同样,发生这种情况的原因是锁对象不存在,也无法复制,并且无论为某个锁指定了什么变量,它都将指向原始对象