python多进程,通过内存共享来通信,使用进程锁来防止数据问题

代码:

import multiprocessing
import time
    
    
'''
使用锁和multiprocessing.Value,multiprocessing.Array,multiprocessing.Manager().list
'''
def worker1(shared_number1, lock):
    for _ in range(10):
        with lock:
            shared_number1.value += 1
    
def worker2(shared_array1, lock):
    for i in range(len(shared_array1)):
        with lock:
            shared_array1[i] += 1

'''
不使用锁
'''
shared_number2 = 0
shared_array2 = [0,1,2,3,4,5,6,7,8,9]

def worker11():
    global shared_number2
    for _ in range(10):
        shared_number2 += 1
    time.sleep(1)
    
def worker22():
    global shared_array2
    for i in range(len(shared_array2)):
        shared_array2[i] += 1
    
    time.sleep(1)

if __name__ == '__main__':
    shared_number1 = multiprocessing.Value('i', 0)
    shared_array1 = multiprocessing.Array('i', [0,1,2,3,4,5,6,7,8,9])
    lock1 = multiprocessing.Lock()
    lock2 = multiprocessing.Lock()
    
    processes1 = []
    for _ in range(100):
        p = multiprocessing.Process(target=worker1, args=(shared_number1, lock1))
        processes1.append(p)
        p.start()
    
    processes2 = []
    for _ in range(100):
        p = multiprocessing.Process(target=worker2, args=(shared_array1, lock2))
        processes2.append(p)
        p.start()
    
    for p in processes1:
        p.join()
    
    for p in processes2:
        p.join()
    
    
    print('使用锁的情况下:')
    print(f"最终的共享数字是: {shared_number1.value}")
    print(shared_array1[:])
    print()
    
    processes11 = []
    for _ in range(100):
        p = multiprocessing.Process(target=worker11, args=())
        processes11.append(p)
        p.start()
    
    processes22 = []
    for _ in range(100):
        p = multiprocessing.Process(target=worker22, args=())
        processes22.append(p)
        p.start()
    
    for p in processes11:
        p.join()
    
    for p in processes22:
        p.join()
    
    #time.sleep(5)
    
    
    print('不使用锁的情况下:')
    print(f"最终的共享数字是: {shared_number2}")
    print(shared_array2[:])

 

import multiprocessing

def calculate_squares(numbers, shared_list):
    for n in numbers:
        shared_list.append(n * n)

def calculate_cubes(numbers, cube_list):
    for n in numbers:
        cube_list.append(n * n * n)

if __name__ == "__main__":
    # 创建Manager对象
    manager = multiprocessing.Manager()
    square_list = manager.list()  # 共享平方列表
    cube_list = manager.list()     # 共享立方列表

    numbers = [1, 2, 3, 4, 5]

    # 创建进程,启动进程
    process1 = multiprocessing.Process(target=calculate_squares, args=(numbers, square_list))
    process2 = multiprocessing.Process(target=calculate_cubes, args=(numbers, cube_list))
    
    process1.start()
    process1.join()  # 等待进程结束

    process2.start()
    process2.join()  # 等待进程结束

    print("共享平方结果:", list(square_list))
    print("共享立方结果:", list(cube_list))

 

输出:

使用锁的情况下:
最终的共享数字是: 1000
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]

不使用锁的情况下:
最终的共享数字是: 0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

共享平方结果: [1, 4, 9, 16, 25]
共享立方结果: [1, 8, 27, 64, 125]

 

posted @ 2024-12-25 20:35  河北大学-徐小波  阅读(3)  评论(0编辑  收藏  举报