一、python多线程其实在底层来说只是单线程,因此python多线程也称为假线程,之所以用多线程的意义是因为线程不停的切换这样比串行还是要快很多。python多线程中只要涉及到io或者sleep就会切换线程。因此在io密集型的情况下可以用多线程。

二、python的多进程是直接调用原生进程,相当于直接调用硬件资源,可以实现多核的功能。

  1、启动两个进程

 #!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-26
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 from multiprocessing import Process
import time def f(name):
time.sleep(2)
print("hello",name) if __name__ == "__main__":
p = Process(target=f,args=("bob",))
p2 = Process(target=f, args=("bob",))
p.start()
p2.start()
p.join()

  2、启动子进程

 #!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-26
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 from multiprocessing import Process
import os def info(title):
print(title)
print("module name:",__name__)
print("parent process:",os.getppid())
print("process id:",os.getpid())
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=f,args=("bob",))
p.start()
p.join()

  执行结果:

C:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.exe E:/PythonLearn/day15/multiprocessing_learn.py
main process line
module name: __main__
parent process: 7308 #这是pycharm的进程号,也是主程序的主进程
process id: 9724  #这是主程序的进程 function f
module name: __mp_main__
parent process: 9724 #这是子进程的父进程,也就是主程序的进程
process id: 3108  #这是子进程id

三、进程间通讯。

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

    a、Queues,使用方法跟threading里的queue差不多

 #!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-26
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 from multiprocessing import Process,Queue
#Queue相当于给数据加了一把锁,只能按顺序排队取,在进程中使用Queue def f(q):
q.put([42,None,"hello"]) if __name__ == "__main__":
q = Queue()
p = Process(target=f,args=(q,)) #在子进程里put一个数据
p.start()
print(q.get()) #在父进程中get
p.join()

  执行结果: 

C:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.exe E:/PythonLearn/day15/multiprocessing_learn.py
[42, None, 'hello']

    b、多个进程向队列中写数据

#!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-26
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 from multiprocessing import Process,Queue
#Queue相当于给数据加了一把锁,只能按顺序排队取,在进程中使用Queue def f(q):
q.put([42,None,"hello"]) if __name__ == "__main__":
q = Queue()
p = Process(target=f,args=(q,)) #在子进程里put一个数据
p2 = Process(target=f, args=(q,)) # 在子进程里put一个数据
p.start()
p2.start()
print("from parent",q.get()) #在父进程中get
print("from parent2",q.get())
print("from parent3",q.get())#因为已经被取完了所以没有了
p.join()

  执行结果:

C:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.exe E:/PythonLearn/day15/multiprocessing_learn.py
from parent [42, None, 'hello']
from parent2 [42, None, 'hello']

四、Pipes,和Queue差不多,也可以一对多。

 #!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-27
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 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,)) #子进程里send一个数据然后关闭
p2 = Process(target=f, args=(child_conn,)) # 子进程里send一个数据然后关闭
p.start()
p2.start()
print(parent_conn.recv()) #prints "[42,None,"hello"]"
print(parent_conn.recv())
p.join()

  执行结果:

C:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.exe E:/PythonLearn/day15/multiprocessing_learn.py
[42, None, 'hello']
[42, None, 'hello'] Process finished with exit code 0

五、进程间实现数据共享 Manager

 #!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-27
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 #进程间实现数据共享
from multiprocessing import Process,Manager #导入Manager def f(d,l,n):
d[n] = n
d[""] = 2
d[0.25] = None
l.append(n)
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,i))
p.start()
p_list.append(p)
for res in p_list:
res.join()
print(d)
print(l)

执行结果:

C:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.exe E:/PythonLearn/day15/multiprocessing_learn.py
[0, 1, 2, 3, 4, 3]
[0, 1, 2, 3, 4, 3, 2]
[0, 1, 2, 3, 4, 3, 2, 6]
[0, 1, 2, 3, 4, 3, 2, 6, 1]
[0, 1, 2, 3, 4, 3, 2, 6, 1, 7]
[0, 1, 2, 3, 4, 3, 2, 6, 1, 7, 0]
[0, 1, 2, 3, 4, 3, 2, 6, 1, 7, 0, 4]
[0, 1, 2, 3, 4, 3, 2, 6, 1, 7, 0, 4, 9]
[0, 1, 2, 3, 4, 3, 2, 6, 1, 7, 0, 4, 9, 5]
[0, 1, 2, 3, 4, 3, 2, 6, 1, 7, 0, 4, 9, 5, 8]
{3: 3, '': 2, 0.25: None, 2: 2, 6: 6, 1: 1, 7: 7, 0: 0, 4: 4, 9: 9, 5: 5, 8: 8}
[0, 1, 2, 3, 4, 3, 2, 6, 1, 7, 0, 4, 9, 5, 8] Process finished with exit code 0

六、进程同步

  python3默认进程会自动加锁,但是python2不会

 #!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-27
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 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()

  执行结果:

 C:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.exe E:/PythonLearn/day15/multiprocessing_learn.py
hello world 3
hello world 6
hello world 2
hello world 7
hello world 0
hello world 5
hello world 1
hello world 4
hello world 8
hello world 9 Process finished with exit code 0

七、进程池

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

  2、进程池中有两个方法:

    a、apply 同步

    b、apply_async 异步

#!/usr/bin/python
# -*- coding : utf-8 -*-
# 作者: Presley
# 时间: 2018-11-27
# 邮箱:1209989516@qq.com
# 这是我用来练习python多进程的测试脚本 from multiprocessing import Process,Pool,freeze_support #在windows上需要导入freeze_support这个包使用,linux上不需要
import time def Foo(i):
time.sleep(2)
return i + 100 def Bar(arg):
print("--> exec done",arg) if __name__ == '__main__':
freeze_support()
pool = Pool(5) #允许最大五个进程同时运行 for i in range(10):
pool.apply_async(func=Foo,args=(i,),callback=Bar)
#callback是回调函数,就是函数Foo执行完了再执行Bar,Foo的执行结果会自动传给Bar,就相当于打印出Foo的执行结果
#pool.apply(func=Foo,args=(i,)) #这个是同步,是串行执行,同步的时候不能使用callback方法 print("end")
pool.close()
pool.join() #进程池中执行完毕后再关闭,如果注释,那么程序直接关闭,按理来说应该程序执行完后再关闭线程池,但是python里面的写法就是这样的

  执行结果:因为允许最大五个进程同时运行因此会每次先打印五个

C:\Users\wohaoshuai\AppData\Local\Programs\Python\Python36\python.exe E:/PythonLearn/day15/multiprocessing_learn.py
end
--> exec done 100
--> exec done 101
--> exec done 102
--> exec done 103
--> exec done 104
--> exec done 105
--> exec done 106
--> exec done 107
--> exec done 108
--> exec done 109 Process finished with exit code 0

Python 多进程multiprocessing的更多相关文章

  1. Python 多进程 multiprocessing.Pool类详解

    Python 多进程 multiprocessing.Pool类详解 https://blog.csdn.net/SeeTheWorld518/article/details/49639651

  2. Python多进程multiprocessing使用示例

    mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多. import multipr ...

  3. python ---多进程 Multiprocessing

    和 threading 的比较 多进程 Multiprocessing 和多线程 threading 类似, 他们都是在 python 中用来并行运算的. 不过既然有了 threading, 为什么 ...

  4. python多进程-----multiprocessing包

    multiprocessing并非是python的一个模块,而是python中多进程管理的一个包,在学习的时候可以与threading这个模块作类比,正如我们在上一篇转载的文章中所提,python的多 ...

  5. python多进程multiprocessing Pool相关问题

    python多进程想必大部分人都用到过,可以充分利用多核CPU让代码效率更高效. 我们看看multiprocessing.pool.Pool.map的官方用法 map(func, iterable[, ...

  6. 操作系统OS,Python - 多进程(multiprocessing)、多线程(multithreading)

    多进程(multiprocessing) 参考: https://docs.python.org/3.6/library/multiprocessing.html 1. 多进程概念 multiproc ...

  7. python多进程(multiprocessing)

    最近有个小课题,需要用到双进程,翻了些资料,还算圆满完成任务.记录一下~ 1.简单地双进程启动 同时的调用print1()和print2()两个打印函数,代码如下: #/usr/bin/python ...

  8. python多进程multiprocessing模块中Queue的妙用

    最近的部门RPA项目中,小爬为了提升爬虫性能,使用了Python中的多进程(multiprocessing)技术,里面需要用到进程锁Lock,用到进程池Pool,同时利用map方法一次构造多个proc ...

  9. Python(多进程multiprocessing模块)

    day31 http://www.cnblogs.com/yuanchenqi/articles/5745958.html 由于GIL的存在,python中的多线程其实并不是真正的多线程,如果想要充分 ...

随机推荐

  1. 2-HTML Text Formatting Elements

    下表列举了文字格式常见的关键字 Tag Description <b> Defines bold text <em> Defines emphasized text  < ...

  2. Thread Synchronization Queue with Boost

    介绍:当开发一个多线程程序时,同步是一个很大的问题.如果你的程序需要数据流包,那么用队列是个好办法. 你可以在 http://www.boost.org/ 发现 boost 库和文档,从它的网站可以看 ...

  3. SQL Server异常汇总

    1.特定用户名无法访问数据库 例如需要使用sa用户名访问School数据库失败,提示如下: (你要设置的)数据库--属性--文件--所用者设为Sa,回到用户映射查看,已勾选上. 还有一些情况 1)将登 ...

  4. jenkins每次构建前删除工作目录操作

    背景: 想在拉取代码前,删除代码,结果百度白天找到答案,mark下 需要安装Workspace Cleanup Plugin插件, 再看创建任务项,勾选即可实现

  5. 搭建python的虚拟环境

    文章连接:https://www.cnblogs.com/zlsgh/p/8485848.html ubuntu系统下Python虚拟环境的安装和使用        前言:进行python项目开发的时 ...

  6. 图解Metrics, tracing, and logging

    Logging,Metrics 和 Tracing   最近在看Gophercon大会PPT的时候无意中看到了关于Metrics,Tracing和Logging相关的一篇文章,凑巧这些我基本都接触过, ...

  7. GDOI2018 滑稽子图 [斯特林数,树形DP]

    传送门并没有 思路 见到那么小的\(k\)次方,又一次想到斯特林数. \[ ans=\sum_{T} f(T)^k = \sum_{i=0}^k i!S(k,i)\sum_{T} {f(T)\choo ...

  8. 【进阶1-3期】JavaScript深入之内存空间详细图解(转)

    这是我在公众号(高级前端进阶)看到的文章,现在做笔记 https://mp.weixin.qq.com/s/x4ZOYysb9XdT1grJbBMVkg 今天介绍的是JS内存空间,了解内存空间中的堆和 ...

  9. day11 函数的位置形参,位置实参,可变长位置形参,关键字形参

    今天内容 函数的参数详解 形参与实参 形参及形式参数,就是在定义函数是括号中指定的参数(本质就是一个名字) 实参及实际参数,指的是在调用函数是传入的参数)(本质就是一个值) 在调用函数是就会把形参和实 ...

  10. hdu2871 区间合并(类似poj3667)+vector应用

    用vector进行插入和删除操作! 总是有些地方处理不好,对拍了才知道错在哪里,, /* 给定一些操作 reset 清空 new a ,申请最左边的连续a个空间 free a,清空a所在的块 get ...