Python2中的锁对象有超时吗?

2024-09-30 20:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用python学习多线程。我写了一些代码来练习

import threading
import time

Total = 0
class myThead(threading.Thread):

    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num
        self.lock = threading.Lock()
    def run(self):
        global Total
        self.lock.acquire()
        print "%s acquired" % threading.currentThread().getName()
        for i in range(self.num):
            Total += 1
        print Total
        print "%s released" % threading.currentThread().getName()
        self.lock.release()

t1 = myThead(100)
t2 = myThead(100)
t1.start()
t2.start()

如果正确的话,通过t1和t2。在

^{pr2}$

但当我试着用更大的麻木。举个例子,我过一万。它打印出意外的输出。在

Thread-1 acquired
Thread-2 acquired
14854
Thread-1 released
15009
Thread-2 released

我试了很多次,但没有改变。所以我认为python中的Lock对象有超时。如果锁获取时间过长,将允许其他线程可以去。谁能给我解释一下吗。谢谢您!在


Tags: importselflockinitdefthreadnumtotal
2条回答

每个线程都有自己的锁,所以获取t1的锁并不能阻止t2获取自己的锁。在

也许您可以使lock成为一个类属性,因此{}的所有实例共享一个。在

class myThead(threading.Thread):
    lock = threading.Lock()

    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num

结果:

^{pr2}$

不,锁没有超时。事实上,它们并不共享同一个锁,因为每次在init方法中实例化对象时,都会创建一个新的锁。如果该类的所有实例始终共享同一个锁,则可以将其作为类属性抛出。然而,显式比隐式好。我个人会把锁作为init方法中的一个参数。像这样。在

import threading
import time

Total = 0
class myThead(threading.Thread):

    def __init__(self, num, lock):
        threading.Thread.__init__(self)
        self.num = num
        self.lock = lock


    def run(self):
        global Total
        self.lock.acquire()
        print "%s acquired" % threading.currentThread().getName()
        for i in range(self.num):
            Total += 1
        print Total
        print "%s released" % threading.currentThread().getName()
        self.lock.release()

threadLock = threading.Lock()
t1 = myThead(100, threadLock)
t2 = myThead(100, threadLock)
t1.start()
t2.start()

这样,类的两个实例共享同一个锁。在

相关问题 更多 >