[b0039] python 归纳 (二四)_多进程数据共享和同步_锁Lock&RLock

# -*- coding: utf-8 -*-
"""
多进程 锁使用

逻辑:
    10个进程各种睡眠2秒,然后打印。
    不加锁同时打印出来,总共2秒,加锁一个接一个打印,总共20秒

总结:
    1、Lock 只要1把锁,RLock 有多把锁,但是不清楚什么场景只适合用RLock

使用:
    1. 创建所   lock = Lock() or lock = RLock()
    2. 把锁当做参数传入给子进程
    3. 在子进程执行代码中对代码块,加锁 lock.acquire(); 其他代码 lock.release()

"""

from multiprocessing import Process, Lock, RLock
import    time

# 不加锁
def f(l, i):
    time.sleep(2)
    print(time.strftime('%M:%S', time.localtime(time.time())),'hello world', i)

# 加Lock
def f2(l, i):
    l.acquire()  # 竞争锁
    time.sleep(2)
    print(time.strftime('%M:%S', time.localtime(time.time())),'hello world', i)
    l.release()  # 释放锁


# 加Rlock
def f3(l, i):
    l.acquire() # 竞争锁
    l.acquire() #  抢到锁后,再加一把锁
    time.sleep(2)
    print(time.strftime('%M:%S', time.localtime(time.time())),'hello world', i)
    l.release() # 释放锁
    l.release() # 前面几个acquire,这里就有几个 release 如果注释掉,其他进程阻塞

if __name__ == '__main__':
    lock = Lock()
    rlock = RLock()

    import ptools;ptools.checkname(rlock);exit(0)


    # base
    # for num in range(10):
    #     Process(target=f, args=(None, num)).start()

    # case1
    for num in range(10):
        Process(target=f2, args=(lock, num)).start()
    #
    # # case2
    # for num in range(10):
    #     Process(target=f3, args=(rlock, num)).start()

"""
Out:
不加锁
('49:31', 'hello world', 3)
('49:31', 'hello world', 2)
('49:31', 'hello world', 1)
('49:31', 'hello world', 7)
('49:31', 'hello world', 8)
('49:31', 'hello world', 5)
('49:31', 'hello world', 6)
('49:31', 'hello world', 4)
('49:31', 'hello world', 9)
('49:31', 'hello world', 0)

case1 加锁,case2差不多
'49:52', 'hello world', 0)
('49:54', 'hello world', 7)
('49:56', 'hello world', 2)
('49:58', 'hello world', 5)
('50:00', 'hello world', 4)
('50:02', 'hello world', 3)
('50:04', 'hello world', 8)
('50:06', 'hello world', 1)
('50:08', 'hello world', 6)
('50:10', 'hello world', 9)
"""

 

posted @ 2018-09-12 22:01  sunzebo  阅读(395)  评论(0编辑  收藏  举报