一、多进程

1.子进程永远返回0,而父进程返回子进程的ID。这样做的理由是,一个父进程可以fork出很多子进程,所以,父进程要记下每个子进程的ID,而子进程只需要调用getppid()就可以拿到父进程的ID。

2.multiprocessing

multiprocessing模块提供了一个Process类来代表一个进程对象,下面的例子演示了启动一个子进程并等待其结束

 import os,time,random
from multiprocessing import Process
#运行多个子进程
def run_child_process(name):
print("run child process %s(%s)"%(name,os.getpid())) if __name__=='__main__':
print("parent process %s"%os.getpid())
p1=Process(target=run_child_process,args=("p1",))
p1.start()
p1.join()
print("child process end")

3.进程池 pool

如果要启动大量的子进程,可以用进程池的方式批量创建子进程:

 from multiprocessing import Pool
import os,time,random
def long_time_task(name):
print("run task %s(%s)"%(name,os.getpid()))
start=time.time()
time.sleep(random.random()*3)
end=time.time()
print("task %s takes %0.2f seconds"%(name,(end-start))) if __name__=='__main__':
print("parent process %s"%os.getpid())
p=Pool(4)
#pool的默认值是cpu数
for i in range(5):
p.apply_async(long_time_task,args=(i,))
print("waiting for all subprocess done")
p.close()
p.join()
print("all subprocess done")

执行结果:

Parent process 4984.
Waiting for all subprocesses done...
Run task 3 (9496)...
Task 3 runs 1.65 seconds.
Run task 4 (9496)...
Task 4 runs 0.16 seconds.
Run task 0 (11036)...
Task 0 runs 2.25 seconds.
Run task 2 (8680)...
Task 2 runs 2.67 seconds.
Run task 1 (11100)...
Task 1 runs 2.97 seconds.
All subprocesses done.
[Finished in 3.7s]

二、多线程

多任务可以由多进程完成,也可以由一个进程内的多线程完成。

我们前面提到了进程是由若干线程组成的,一个进程至少有一个线程

1.启动线程

 import threading,time
def loop():
print("thread %s is running..."%threading.current_thread().name)
n=0
while n<5:
n=n+1
print("thread %s>>>%s"%(threading.current_thread().name,n))
time.sleep(1)
print("thread %s is ended"%threading.current_thread().name)
print("thread %s is running"%threading.current_thread().name)
t=threading.Thread(target=loop,name="loopthread")
t.start()
t.join()
print("thread %s is ended"%threading.current_thread().name)

执行结果:

 thread MainThread is running
thread loopthread is running...
thread loopthread>>>1
thread loopthread>>>2
thread loopthread>>>3
thread loopthread>>>4
thread loopthread>>>5
thread loopthread is ended
thread MainThread is ended
[Finished in 5.3s]

2.lock

多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了

 import time,threading
balance=0
lock=threading.Lock()
def change_it(n):
global balance
balance=balance+n
balance=balance-n def run_thread(n):
for i in range(100000):
lock.acquire()
try:
change_it(n)
finally:
lock.release()
t1=threading.Thread(target=run_thread,args=(5,))
t2=threading.Thread(target=run_thread,args=(8,))
t1.start()
t2.start()
t1.join()
t1.join()
print(balance)

三、队列

1.Process之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了QueuePipes等多种方式来交换数据。

我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:

 from multiprocessing import Process, Queue
import os, time, random
# 写数据进程执行的代码:
def write(q):
print('Process to write: %s' % os.getpid())
for value in ['A', 'B', 'C']:
print('Put %s to queue...' % value)
q.put(value)
time.sleep(random.random()) # 读数据进程执行的代码:
def read(q):
print('Process to read: %s' % os.getpid())
while True:
value = q.get(True)
print('Get %s from queue.' % value) if __name__=='__main__':
# 父进程创建Queue,并传给各个子进程:
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 启动子进程pr,读取:
pr.start()
# 等待pw结束:
pw.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()

原文地址:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431927781401bb47ccf187b24c3b955157bb12c5882d000

https://yuedu.baidu.com/ebook/0f6a093b7dd184254b35eefdc8d376eeaeaa17e3?pn=1&rf=https%3A%2F%2Fyuedu.baidu.com%2Febook%2F0f6a093b7dd184254b35eefdc8d376eeaeaa17e3

【python】多进程、多线程、序列的更多相关文章

  1. Python 多进程 多线程 协程 I/O多路复用

    引言 在学习Python多进程.多线程之前,先脑补一下如下场景: 说有这么一道题:小红烧水需要10分钟,拖地需要5分钟,洗菜需要5分钟,如果一样一样去干,就是简单的加法,全部做完,需要20分钟:但是, ...

  2. python 多进程/多线程/协程 同步异步

    这篇主要是对概念的理解: 1.异步和多线程区别:二者不是一个同等关系,异步是最终目的,多线程只是我们实现异步的一种手段.异步是当一个调用请求发送给被调用者,而调用者不用等待其结果的返回而可以做其它的事 ...

  3. python 多进程多线程的对比

    link:http://www.cnblogs.com/whatisfantasy/p/6440585.html mark一下,挺详细

  4. Python的多线程(threading)与多进程(multiprocessing )

    进程:程序的一次执行(程序载入内存,系统分配资源运行).每个进程有自己的内存空间,数据栈等,进程之间可以进行通讯,但是不能共享信息. 线程:所有的线程运行在同一个进程中,共享相同的运行环境.每个独立的 ...

  5. 【转】【Python】Python多进程与多线程

    1.1 multiprocessing multiprocessing是多进程模块,多进程提供了任务并发性,能充分利用多核处理器.避免了GIL(全局解释锁)对资源的影响. 有以下常用类: 类 描述 P ...

  6. python采用 多进程/多线程/协程 写爬虫以及性能对比,牛逼的分分钟就将一个网站爬下来!

    首先我们来了解下python中的进程,线程以及协程! 从计算机硬件角度: 计算机的核心是CPU,承担了所有的计算任务.一个CPU,在一个时间切片里只能运行一个程序. 从操作系统的角度: 进程和线程,都 ...

  7. python 多进程开发与多线程开发

    转自: http://tchuairen.blog.51cto.com/3848118/1720965 博文作者参考的博文:  博文1  博文2 我们先来了解什么是进程? 程序并不能单独运行,只有将程 ...

  8. Python多进程、多线程、协程

    转载:https://www.cnblogs.com/huangguifeng/p/7632799.html 首先我们来了解下python中的进程,线程以及协程! 从计算机硬件角度: 计算机的核心是C ...

  9. Python之多线程和多进程

    一.多线程 1.顺序执行单个线程,注意要顺序执行的话,需要用join. #coding=utf-8 from threading import Thread import time def my_co ...

  10. 也说性能测试,顺便说python的多进程+多线程、协程

    最近需要一个web系统进行接口性能测试,这里顺便说一下性能测试的步骤吧,大概如下 一.分析接口频率 根据系统的复杂程度,接口的数量有多有少,应该优先对那些频率高,数据库操作频繁的接口进行性能测试,所以 ...

随机推荐

  1. spring boot入门学习---1

    1.maven配置 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="h ...

  2. 从库因为sql错误导致主从同步被中断的问题解决

    从库因为sql错误导致主从同步被中断的问题解决:show slave status\G;看lasterror:看延迟多少秒,正常情况下是没有延迟的. 跳过错误的那条sql:SET GLOBAL SQL ...

  3. 微信小程序 左右分类滚动列表

    今天需求个类似得到app分类的功能,效果如图: 左右分别滚动,互不干扰,先把简单的布局和样式搭好. <view class="page"> <view class ...

  4. Flutter 异步Future与FutureBuilder实用技巧

    什么是Future? Future表示在接下来的某个时间的值或错误,借助Future我们可以在Flutter实现异步操作.它类似于ES6中的Promise,提供then和catchError的链式调用 ...

  5. linux ssh利用公钥免密登陆

    1.安装检查ssh 如果没有ssh的话,需要安装 #yum  install -y openssh-server openssh-clients 2.生成秘钥 ssh-keygen -t rsa 执行 ...

  6. 虚拟机中CentOS 7 x64图形化界面的安装

    VMware的初始设置如下: 图1 待虚拟机读取完iso,出现此界面 图2 我们主要是安装图形化界面的系统,所以在软件选择栏下如图选择: 图3 设置root密码,创建用户,等候安装完成: 图4 安装完 ...

  7. sql server新旧数据库的表结构差异

    sql server编写通用脚本自动检查两个不同服务器的新旧数据库的表结构差异 问题:工作过程中,不管是什么项目,伴随着项目不断升级版本,对应的项目数据库业务版本也不断升级,数据库出现新增表.修改表. ...

  8. 如何使用 Issue 管理软件项目?

    软件开发(尤其是商业软件)离不开项目管理,Issue 是最通用的管理工具之一.

  9. [LuoguP1264]K-联赛_网络流

    K-联赛 题目链接:https://www.luogu.org/problem/P1264 数据范围:略. 题解: 首先,枚举所有球队是否作为答案是必须的. 因为发现$n$实在是特别小,很容易想到网络 ...

  10. axios 使用post方式传递参数,后端接收不到

    最近做vue项目,做图片上传的功能,使用get给后台发送数据,后台能收到,使用post给后台发送图片信息的时候,vue axios post请求发送图片base64编码给后台报错HTTP 错误 414 ...