了解MultiThreading和锁定Python

时间:2016-05-24 13:51:09

标签: python multithreading

我试图理解以下代码:一个线程(比如说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()

打印“退出主线程”

1 个答案:

答案 0 :(得分:1)

锁定是一种确保一次最多只有一个线程正在执行关键部分的方法。它是一个具有锁定和解锁两种状态的对象。如果它已解锁,则调用其dte.ExecuteCommand("Edit.Replace"); dte.Find.FindWhat = "\"(.+?)\"|'(.+?)'"; dte.Find.ReplaceWith = "$1" dte.Find.Target = vsFindTarget.vsFindTargetCurrentDocument dte.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr dte.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone dte.Find.Action = vsFindAction.vsFindActionReplace dte.Find.Execute() 方法会将其锁定。如果第二次调用acquire()(通常由另一个线程),则此调用将阻塞调用线程,直到有人(通常是第一个线程)使用acquire()方法释放锁定。只有这样,第二个线程才能继续。

在您的示例中,锁定确保首先获得它的线程"将在第二个线程打印任何内容之前打印release()函数中的所有行。如果您删除/评论print_time()acquire()来电,差异应该很明显。

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