Python线程.如何锁定线程?

Zac*_*ack 58 python multithreading

我正在尝试理解线程和并发的基础知识.我想要一个简单的情况,其中两个线程反复尝试访问一个共享资源.

代码:

import threading

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()
count = 0
lock = threading.Lock()

def incre():
    global count 
    lock.acquire()
    try:
        count += 1    
    finally:
        lock.release()

def bye():
    while True:
        incre()

def hello_there():
    while True:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)

    while True:
        print count

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

所以,我有两个线程,都试图增加计数器.我认为如果线程'A'被调用incre(),那么lock就会建立起来,阻止'B'访问,直到'A'被释放.

运行时清楚地表明情况并非如此.您将获得所有随机数据竞争增量.

锁对象究竟是如何使用的?

编辑,另外,我已经尝试将锁定放在线程函数内部,但仍然没有运气.

jdi*_*jdi 71

你可以看到你的锁在使用它们时非常有效,如果你减慢了进程并使它们阻塞了一点.你有正确的想法,用锁来包围关键的代码片段.这是对您的示例的一个小调整,以向您展示每个人如何等待释放锁.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

样本输出:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...
Run Code Online (Sandbox Code Playgroud)

  • 哦,整洁!我想我对“main()”中显示不稳定迭代的“打印计数”感到困惑。但我想这可能是因为我同时运行了三个循环。谢谢!还有关于检查模块的 TIL。很酷。 (2认同)