首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解MultiThreading和Locks Python

理解MultiThreading和Locks Python
EN

Stack Overflow用户
提问于 2016-05-24 13:51:09
回答 1查看 194关注 0票数 0

我试图理解以下代码:线程(例如Thread1)获取锁意味着什么,这是否意味着在Thread1释放其锁之前没有其他方法可以运行?

代码语言:javascript
复制
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()

打印“退出主线程”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-24 13:59:11

锁是一种确保一次最多只执行一个线程的方法。它是一个有两种状态的对象,被锁定和未锁定。如果它被解锁,对其acquire()方法的调用将锁定它。如果对acquire()进行第二次调用(通常由另一个线程进行),则此调用将阻塞调用线程,直到某个人(通常是第一个线程)用release()方法释放锁为止。只有这样,第二个线程才能继续。

在您的示例中,锁确保“先获得它”的线程将在第二个线程打印任何内容之前打印print_time()函数中的所有行。如果删除/注释acquire()release()调用,两者之间的区别应该是显而易见的。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37415667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档