背景
客户端程序从rabbitmq消费,然后根据消息到远程服务器写密钥文件 authorized_keys
等一系列操作, 如果同时到来两条消,可能导致异常。
代码加锁
lock = threading.Lock()
def write(thread_id):
#
with lock:
print(f'thread:{thread_id} line start')
time.sleep(1)
print(f'thread {thread_id}line end')
测试代码
import threading
from concurrent.futures import ThreadPoolExecutor
# 创建锁
lock = threading.Lock()
def write(thread_id):
with lock:
print(f'thread:{thread_id} line start')
# 模拟操作过程 ,防止程序迅速结束
time.sleep(1)
print(f'thread {thread_id}line end')
if __name__ == '__main__':
# 多线程调用
pool = ThreadPoolExecutor(10)
pool.map(write, [i for i in range(1,11)])