简体   繁体   English

Python线程。 如何锁定线程?

[英]Python threading. How do I lock a thread?

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.我想要一个简单的案例,其中两个线程反复尝试访问一个共享资源。

The code:代码:

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

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.我认为如果线程 'A' 调用了incre() ,则会建立lock ,阻止 'B' 访问,直到 'A' 释放。

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

Sample output:示例输出:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...
import threading # global variable x x = 0 def increment(): """ function to increment global variable x """ global x x += 1 def thread_task(): """ task for thread calls increment function 100000 times. """ for _ in range(100000): increment() def main_task(): global x # setting global variable x as 0 x = 0 # creating threads t1 = threading.Thread(target=thread_task) t2 = threading.Thread(target=thread_task) # start threads t1.start() t2.start() # wait until threads finish their job t1.join() t2.join() if __name__ == "__main__": for i in range(10): main_task() print("Iteration {0}: x = {1}".format(i,x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM