python类库32[多进程同步Lock+Semaphore+Event]

 

同步的方法基本与多线程相同。

1) Lock

当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突。


import multiprocessing
import sys def worker_with(lock, f):
    with lock:
        fs = open(f,"a+")
        fs.write('Lock acquired via with\n')
        fs.close()
        
def worker_no_with(lock, f):
    lock.acquire()
    try:
        fs = open(f,"a+")
        fs.write('Lock acquired directly\n')
        fs.close()
    finally:
        lock.release() if __name__ == "__main__":     f = "file.txt"
  
    lock = multiprocessing.Lock()
    w = multiprocessing.Process(target=worker_with, args=(lock, f))
    nw = multiprocessing.Process(target=worker_no_with, args=(lock, f))     w.start()
    nw.start()     w.join()
    nw.join()
 
在上面的例子中,如果两个进程没有使用lock来同步,则他们对同一个文件的写操作可能会出现混乱。

2)Semaphore

Semaphore用来控制对共享资源的访问数量,例如池的最大连接数。


import multiprocessing
import time  def worker(s,i):
    s.acquire()
    print(multiprocessing.current_process().name + " acquire")
    time.sleep(i)
    print(multiprocessing.current_process().name + " release")
    s.release() if __name__ == "__main__":
  
    s = multiprocessing.Semaphore(2)
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(s,i*2))
        p.start()

上面的实例中使用semaphore限制了最多有2个进程同时执行。

3)Event

Event用来实现进程间同步通信。


import multiprocessing
import time def wait_for_event(e):
    """Wait for the event to be set before doing anything"""
    print ('wait_for_event: starting')
    e.wait()
    print ('wait_for_event: e.is_set()->' + str(e.is_set())) def wait_for_event_timeout(e, t):
    """Wait t seconds and then timeout"""
    print ('wait_for_event_timeout: starting')
    e.wait(t)
    print ('wait_for_event_timeout: e.is_set()->' + str(e.is_set())) if __name__ == '__main__':
    e = multiprocessing.Event()
    w1 = multiprocessing.Process(name='block', 
                                 target=wait_for_event,
                                 args=(e,))
    w1.start()     w2 = multiprocessing.Process(name='non-block', 
                                 target=wait_for_event_timeout, 
                                 args=(e, 2))
    w2.start()     time.sleep(3)
    e.set()
    print ('main: event is set')
    
#the output is:
#wait_for_event_timeout: starting
#wait_for_event: starting
#wait_for_event_timeout: e.is_set()->False
#main: event is set
#wait_for_event: e.is_set()->True

参考:http://www.doughellmann.com/PyMOTW/multiprocessing/communication.html

完!

python类库32[多进程同步Lock+Semaphore+Event]的更多相关文章

  1. python类库32[多进程通信Queue+Pipe+Value+Array]

    多进程通信 queue和pipe的区别: pipe用来在两个进程间通信.queue用来在多个进程间实现通信. 此两种方法为所有系统多进程通信的基本方法,几乎所有的语言都支持此两种方法. 1)Queue ...

  2. python lock, semaphore, event实现线程同步

    lock 机制不管你是java, C#, 还是python都是常用的线程同步机制, 相比较C# 的锁机制, python的加锁显得比较简单, 直接调用threading 标准库的lock 就可以了. ...

  3. python类库32[序列化和反序列化之pickle]

      一 pickle pickle模块用来实现python对象的序列化和反序列化.通常地pickle将python对象序列化为二进制流或文件.   python对象与文件之间的序列化和反序列化: pi ...

  4. [b0041] python 归纳 (二六)_多进程数据共享和同步_事件Event

    # -*- coding: utf-8 -*- """ 多进程 同步 事件multiprocessing.Event 逻辑: 子线程负责打印,会阻塞, 等待主进程发出控制 ...

  5. 扯扯python的多线程的同步锁 Lock RLock Semaphore Event Condition

    我想大家都知道python的gil限制,记得刚玩python那会,知道了有pypy和Cpython这样的解释器,当时听说是很猛,也就意味肯定是突破了gil的限制,最后经过多方面测试才知道,还是那德行… ...

  6. python 多线程中的同步锁 Lock Rlock Semaphore Event Conditio

    摘要:在使用多线程的应用下,如何保证线程安全,以及线程之间的同步,或者访问共享变量等问题是十分棘手的问题,也是使用多线程下面临的问题,如果处理不好,会带来较严重的后果,使用python多线程中提供Lo ...

  7. Python系列之 - 锁(GIL,Lock,Rlock,Event,信号量)

    python 的解释器,有很多种,但市场占有率99.9%的都是基于c语言编写的CPython.  在这个解释器里规定了GIL. In CPython, the global interpreter l ...

  8. Python 多线程、多进程 (二)之 多线程、同步、通信

    Python 多线程.多进程 (一)之 源码执行流程.GIL Python 多线程.多进程 (二)之 多线程.同步.通信 Python 多线程.多进程 (三)之 线程进程对比.多线程 一.python ...

  9. python多线程同步机制Semaphore

    #!/usr/bin/env python # -*- coding: utf-8 -*- """ Python 线程同步机制:Semaphore "" ...

随机推荐

  1. CentOS mysql安装

    MySQL For Excel 1.3.5MySQL for Visual Studio 1.2.5MySQL Fabric 1.5.6 & MySQL Utilities 1.5.6Conn ...

  2. js中dom选择器

    document,getElementById("demo");    //通过id查询节点 . document.getElementsByTagName("div&q ...

  3. PEP8-python编码规范(上)

    包含主要 Python 发行版中的标准库的 Python 代码的编码约定. 1.代码缩进 (1)每个缩进需要使用 4 个空格.一般使用一个Tab键. Python 3 不允许混合使用制表符和空格来缩进 ...

  4. python 并发编程 阻塞IO模型

    阻塞IO(blocking IO) 在linux中,默认情况下所有的socket都是blocking,一个典型的读操作流程大概是这样: 当用户进程调用了recvfrom这个系统调用,kernel内核就 ...

  5. windows VS2013中使用<pthread.h>

    1. 下载pthreads-w32-2-9-1-realease.zip 地址:http://www.mirrorservice.org/sites/sourceware.org/pub/pthrea ...

  6. etcd集群添加节点

    查看当前集群节点信息 # etcdctl member list --write-out=table +------------------+---------+------------------- ...

  7. Linux-usermod:增加已建立用户的用户组

    usermod --help -g, --gid GROUP force use GROUP as new primary group -G, --groups GROUPS new list of ...

  8. springboot - 应用实践(2)第一个springboot应用

    1.使用maven创建一个快速启动项目 2.引入相关依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:x ...

  9. Java基础(入门Java)

    今天是学习Java的第一天,为了保证在暑假里持续高效的学习,决定每周写一篇博客汇报总结当周进度,以此来督促自己不断的向更深更远的方向迈进.Java刚刚入门,看到的人若觉得某些地方不妥欢迎进行批评指导, ...

  10. numpy-添加操作大全

    合并 hstack(tup):按行合并 [前面有个 h,可以理解为 行,这样方便记忆] vstack(tup):按列合并 参数虽然是 tuple,但是 list 也行,可以合并2个或者多个数组. a= ...