在并发处理中,锁机制是一种重要的同步手段,用于确保多个线程或进程在访问共享资源时不会发生冲突。以下是锁机制在并发处理中的应用:
import threading
lock = threading.Lock()
shared_resource = 0
def increment():
global shared_resource
with lock:
shared_resource += 1
threads = [threading.Thread(target=increment) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(shared_resource) # 输出应为10
import threading
rw_lock = threading.RLock()
shared_resource = 0
def read_resource():
with rw_lock:
print(f"Reading: {shared_resource}")
def write_resource(value):
global shared_resource
with rw_lock:
shared_resource = value
print(f"Writing: {shared_resource}")
threads = [threading.Thread(target=read_resource) for _ in range(5)] + \
[threading.Thread(target=write_resource, args=(i,)) for i in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
import threading
condition = threading.Condition()
queue = []
def producer():
for i in range(5):
with condition:
queue.append(i)
condition.notify() # 通知等待的消费者
def consumer():
while True:
with condition:
while not queue:
condition.wait() # 等待生产者通知
item = queue.pop(0)
print(f"Consumed: {item}")
threading.Thread(target=producer).start()
threading.Thread(target=consumer).start()
import threading
semaphore = threading.Semaphore(2)
def access_resource(thread_id):
with semaphore:
print(f"Thread {thread_id} is accessing the resource")
# 模拟资源访问
threading.Event().wait(1)
threads = [threading.Thread(target=access_resource, args=(i,)) for i in range(5)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
import threading
barrier = threading.Barrier(3)
def worker(thread_id):
print(f"Thread {thread_id} is waiting at the barrier")
barrier.wait()
print(f"Thread {thread_id} has crossed the barrier")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
通过合理使用这些锁机制,可以有效地管理并发环境中的资源共享和线程同步问题。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。