简体   繁体   English

了解多线程并锁定Python

[英]Understanding MultiThreading and Locks Python

I am trying to understand the following code: What does it mean for a Thread (say Thread1) to acquire a lock, does this mean that no other method can run until Thread1 has released its lock? 我试图理解以下代码:线程(例如Thread1)获得锁是什么意思,这意味着在Thread1释放锁之前没有其他方法可以运行吗?

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        # Get lock to synchronize threads
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # Free lock to release next thread
        threadLock.release()

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1

threadLock = threading.Lock()
threads = []

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

# Add threads to thread list
threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete
for t in threads:
    t.join()

print "Exiting Main Thread" 打印“退出主线程”

A lock is a way to ensure that at most one thread at a time is executing a critical section. 锁是一种确保一次最多一个线程正在执行关键部分的方法。 It is an object with two states, locked and unlocked. 它是具有两种状态(锁定和解锁)的对象。 If it is unlocked, a call to its acquire() method locks it. 如果它是未锁定的,则对其及其acquire()方法的调用将其锁定。 If a second call to acquire() (usually by another thread) is made, this call blocks the calling thread until someone (usually the first thread) releases the lock with the release() method. 如果第二次(通常是另一个线程)对acquire()进行了调用,则此调用将阻塞调用线程,直到有人(通常是第一个线程)使用release()方法释放该锁。 Only then can the second thread continue. 只有这样,第二个线程才能继续。

In your example, the lock ensures that the thread that "gets it first" will print all lines in the print_time() function before the second thread prints anything. 在您的示例中,锁确保“首先获得它”的线程将在第二个线程打印任何内容之前打印出print_time()函数中的所有行。 If you remove/comment the acquire() and release() calls, the difference should be obvious. 如果删除/注释了acquire()release()调用,则区别应该很明显。

https://docs.python.org/2/library/threading.html#lock-objects https://docs.python.org/2/library/threading.html#lock-objects

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

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