Python - 同步线程


Python 提供的线程模块包含一个易于实现的锁定机制,允许您同步线程。通过调用Lock()方法创建一个新锁,该方法返回新锁。

新锁对象的acquire (blocking)方法用于强制线程同步运行。可选的阻塞参数使您能够控制线程是否等待获取锁。

如果阻塞设置为 0,则如果无法获取锁,则线程立即返回 0 值;如果获取锁,则线程立即返回 1。如果阻塞设置为1,则线程阻塞并等待锁被释放。

新锁对象的release ()方法用于在不再需要锁时释放该锁。

例子

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

输出

执行上述代码时,会产生以下输出 -

Starting Thread-1
Starting Thread-2
Thread-1: Thu Jul 13 21:10:11 2023
Thread-1: Thu Jul 13 21:10:12 2023
Thread-1: Thu Jul 13 21:10:13 2023
Thread-2: Thu Jul 13 21:10:15 2023
Thread-2: Thu Jul 13 21:10:17 2023
Thread-2: Thu Jul 13 21:10:19 2023
Exiting Main Thread