multiprocessing

from multiprocessing import Process
import time
def f(name):
time.sleep(2)
print('hello',name) if __name__ == '__main__':
p1 = Process(target=f,args = ('bob',))
p2 = Process(target=f,args=('john',))
p1.start()
p2.start()
p1.join()

显示进程ID 

# !/usr/bin/env python
# -*- coding:utf-8 -*- from multiprocessing import Process
import os def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid()) # 父进程ID
print('process id:', os.getpid()) #自己的进程ID
print("\n\n") def f(name):
info('\033[31;1mfunction f\033[0m')
print('hello', name) if __name__ == '__main__':
info('\033[32;1mmain process line\033[0m')
p = Process(target=info, args=('bob',))
p.start()
p.join()

进程间通讯

不同进程间内存是不共享的,要想实现两个进程间的数据交换,可以用以下方法:

Queues

# !/usr/bin/env python
# -*- coding:utf-8 -*-
from multiprocessing import Process, Queue def f(q):
q.put([42, None, 'hello']) if __name__ == '__main__':
q = Queue() #创建队列
p = Process(target=f, args=(q,))
p2 = Process(target=f, args=(q,))
p.start()
p2.start()
print('from parent',q.get()) #获取子进程put的值
print('from parent',q.get())
p.join()

Pipes

The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex (two-way).

# !/usr/bin/env python
# -*- coding:utf-8 -*- from multiprocessing import Process, Pipe def f(conn):
conn.send([42, None, 'hello']) #发送数据
conn.close() if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p2 = Process(target=f, args=(child_conn,))
p.start()
p2.start()
print(parent_conn.recv()) # 接受数据
print(parent_conn.recv())
p.join()

Managers

A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies.

A manager returned by Manager() will support types listdictNamespaceLockRLockSemaphoreBoundedSemaphoreConditionEventBarrierQueueValue and Array.

# !/usr/bin/env python
# -*- coding:utf-8 -*-
from multiprocessing import Process, Manager def f(d, l):
d[1] = ''
d[''] = 2
d[0.25] = None
l.append(1)
print(l) if __name__ == '__main__':
with Manager() as manager:
d = manager.dict()
l = manager.list(range(5))
p_list = []
for i in range(10):
p = Process(target=f, args=(d, l))
p.start()
p_list.append(p)
for res in p_list:
res.join() print(d)
print(l)

进程同步

Without using the lock output from the different processes is liable to get all mixed up.

from multiprocessing import Process, Lock

def f(l, i):
l.acquire()
try:
print('hello world', i)
finally:
l.release() if __name__ == '__main__':
lock = Lock() for num in range(10):
Process(target=f, args=(lock, num)).start()

进程池  

进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。

进程池中有两个方法:

  • apply
  • apply_async
from  multiprocessing import Process,Pool,freeze_support
import time def Foo(i):
time.sleep(4)
print('exec...')
return i+100 def Bar(arg):
print('-->exec done:',arg) if __name__ == '__main__':
freeze_support()
pool = Pool(5)
for i in range(100):
pool.apply_async(func=Foo, args=(i,),callback=Bar)
#pool.apply(func=Foo, args=(i,))
print('end')
pool.close()
pool.join()
#pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。

python学习笔记-多进程的更多相关文章

  1. Python 学习笔记 多进程 multiprocessing--转载

    本文链接地址 http://quqiuzhu.com/2016/python-multiprocessing/ Python 解释器有一个全局解释器锁(PIL),导致每个 Python 进程中最多同时 ...

  2. python 学习笔记 多进程

    要让python程序实现多进程,我们先了解操作系统的相关知识 Unix/Linux操作系统提供了一个fork()系统调用,他非常特殊,普通的函数调用,调用一次,返回一次,但是fork调用一次, 返回两 ...

  3. python学习笔记——多进程中的锁Lock

    1 进程锁 python编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性. 每个对象都对应于一个可称为“互斥锁”的标记,这个标记用来保证在任一时刻,只能有一线程访问对象. 在python中我 ...

  4. python学习笔记——多进程中共享内存Value & Array

    1 共享内存 基本特点: (1)共享内存是一种最为高效的进程间通信方式,进程可以直接读写内存,而不需要任何数据的拷贝. (2)为了在多个进程间交换信息,内核专门留出了一块内存区,可以由需要访问的进程将 ...

  5. python学习笔记—— 多进程中的 孤儿进程和僵尸进程

    1 基本概述 1.1 孤儿进程和僵尸进程 父进程创建子进程后,较为理想状态是子进程结束,父进程回收子进程并释放子进程占有的资源:而实际上,父子进程是异步过程,两者谁先结束是无顺的,一般可以通过父进程调 ...

  6. python学习笔记——多进程二 进程的退出

    1 进程的退出函数的基础语法 1.1 进程的退出函数 进程的退出含有有os._exit([status])和sys.exit([status])两种,从数据包来看,该退出模块仅在linux或者unix ...

  7. python学习笔记——多进程一 基础概念

    1 进程 进程:程序的一次(从开始到结束)执行过程,属于一个动态过程.是系统进行资源分配和调度的基本单位. 程序:指的是一个文件,磁盘中可执行的代码.属于一个静态文件 注:进程运行时需要把程序加载如内 ...

  8. Python学习笔记进阶篇——总览

    Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(Socket编程进阶&多线程.多进程) Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(异常处理) Pyth ...

  9. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

随机推荐

  1. Spark Streaming架构设计和运行机制总结

    本期内容 : Spark Streaming中的架构设计和运行机制 Spark Streaming深度思考 Spark Streaming的本质就是在RDD基础之上加上Time ,由Time不断的运行 ...

  2. ThinkPad W520 在 Windows Server 2012 / R2 中安装驱动

    1.安装Intel Chipset Device Software (INF Update Utility).2.安装ThinkPad ACPI电源管理驱动.3.安装电源管理软件.4.安装英特尔核芯显 ...

  3. spring 注入静态变量

    import java.util.Iterator; import java.util.LinkedList; import javax.annotation.PostConstruct; impor ...

  4. .NET 工具类ObjectDumper 打印对象

    // Comes from the LINQ samples provided by Microsoft //Copyright (C) Microsoft Corporation. All righ ...

  5. Application、 session、iewstate,以及repeater 的commang用法

      Session:在不同的浏览器之间传值,像银行之类的网站为了安全把用户名密码保存在session里面.每一台电脑访问服务器,都会是独立的一套session,key值都一样,但是内容都是不一样的 以 ...

  6. rabbitMQ学习(六)

    请求模式 客户端: import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; impor ...

  7. 总结一些关于操作数据库是sql语句还是存储过程问题

    总结一些关于操作数据库是sql语句还是存储过程问题 程序中,你跟数据的交互,需要向数据库拿数据.更改数据库的数据等,这些操作,本身不是程序完成的,而是程序发命令给数据库去做的,不管是通过sql语句方式 ...

  8. assert的用法

    assert用来调试时,判断一个语句是否为真. assert是宏,而不是函数.在C的assert.h 头文件中. assert的作用是先计算表达式 expression ,如果其值为假(即为0),那么 ...

  9. C# windows form如何隐藏窗口?

    you can use this line of code. It wont hide it, but it will be minimized: this.WindowState = FormWin ...

  10. solrCloud+tomcat+zookeeper集群配置

    solrcolud安装solrCloud+tomcat+zookeeper部署  转载请出自出处:http://eksliang.iteye.com/blog/2107002 http://eksli ...