锁的利用:
锁是通过获取和开释的办法来实现对共享资源的访问掌握。当一个线程获取到锁时,其他线程就无法获取到锁,只能等待锁被开释后才能连续实行。
锁的所有功能:

示例1:利用锁实现对共享变量的互斥访问
import threading# 创建一个锁工具lock = threading.Lock()# 共享资源count = 0# 线程函数def thread_func(): global count for _ in range(100000): # 获取锁 lock.acquire() try: # 对共享资源进行操作 count += 1 finally: # 开释锁 lock.release()# 创建并启动多个线程threads = []for _ in range(4): thread = threading.Thread(target=thread_func) thread.start() threads.append(thread)# 等待线程实行完毕for thread in threads: thread.join()# 打印终极结果print("Final count:", count)
在上述示例中,我们创建了一个锁工具lock,并定义了一个共享变量count。在每个线程的实行函数中,首先通过lock.acquire()获取锁,然后对共享变量进行操作,末了通过lock.release()开释锁。
示例2:锁的可重入性
import threading# 创建一个锁工具lock = threading.Lock()# 线程函数def thread_func(): with lock: print("Outer lock acquired!") with lock: print("Inner lock acquired!")# 创建并启动线程thread = threading.Thread(target=thread_func)thread.start()thread.join()
在上述示例中,我们创建了一个锁工具lock。在线程函数中,通过利用with lock:语句获取锁。在内部锁获取之前,外部锁已经被线程获取,这是由于锁的可重入性。可重入性使得同一个线程可以多次获取同一个锁,而不会导致去世锁。
这些示例展示了锁的利用和常见功能。通过利用锁,可以实现对共享资源的互斥访问,确保多线程程序的精确性和同等性。