Python线程.如何锁定线程? [英] Python threading. How do I lock a thread?

查看:92
本文介绍了Python线程.如何锁定线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to understand the basics of threading and concurrency. I want a simple case where two threads repeatedly try to access one shared resource.

代码:

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()

所以,我有两个线程,都试图增加计数器.我以为如果线程'A'称为incre(),则会建立lock,从而在'A'释放之前阻止'B'访问.

So, I have two threads, both trying to increment the counter. I thought that if thread 'A' called incre(), the lock would be established, preventing 'B' from accessing until 'A' has released.

运行该命令可以清楚地知道情况并非如此.您将获得所有随机数据竞争性增量.

Running the makes it clear that this is not the case. You get all of the random data race-ish increments.

到底如何使用锁对象?

How exactly is the lock object used?

编辑,此外,我尝试将锁放入线程函数中,但还是没有运气.

Edit, Additionally, I've tried putting the locks inside of the thread functions, but still no luck.

推荐答案

您可以看到,如果您减慢了进程的速度并使它们的阻塞程度进一步提高,则在使用它们的过程中锁几乎可以正常工作.您有一个正确的想法,就是用锁将关键代码段包围起来.这是对您的示例的一个小调整,以向您展示如何彼此等待释放锁.

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

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()

示例输出:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

这篇关于Python线程.如何锁定线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆