python多进程编程(python多进程进程池)
off999 2025-07-06 15:51 3 浏览 0 评论
fork
windows中是没有fork函数的,一开始直接在Windows中测试,直接报错
import os
import time
ret = os.fork()
if ret == 0:
while True:
print("-----1----")
time.sleep(1)
else:
while True:
print("-----2-----")
time.sleep(1)
AttributeError: module 'os' has no attribute 'fork'
然后在Linux上实验,可以。父子进程执行顺序是不定的。
fork函数调动一次,有两个返回值,父进程返回值>0,子进程返回值=0;
import os
ret = os.fork()
print(ret)
父进程中fork的返回值就是创建的子进程的pid。
import os
ret = os.fork()
print(ret)
if ret>0:
print("--父进程pid--%d"%os.getpid())
else:
print("--子进程pid--%d--父进程---%d"%(os.getpid(),os.getppid()))
父子进程的退出
父进程可以在子进行前退出。
import os
import time
ret = os.fork()
if ret==1:
print("子进程1")
time.sleep(5)
print("子进程2")
else:
print("父进程")
time.sleep(3)
print("over")
全局变量问题:
变量在父子进程间不会共享,子进程会自己创建一份。
import os
import time
num = 100
ret = os.fork()
if ret==0:
print("----process1----")
num += 1
print("-----process1---num=%d"%(num))
else:
time.sleep(3)
print("---process2----num=%d"%(num))
多次fork问题:
import os
import time
ret = os.fork()
if ret==0:
print("--1--")
else:
print("--2--")
ret = os.fork()
if ret ==0:
print("--11--")
else:
print("--22--")
3个fork问题:
Process创建子进程
multiprocessing模块中Process类
rom multiprocessing import Process
import time
def test():
while True:
print("--test--")
time.sleep(1)
p = Process(target=test)//创建一个进程对象,test函数结束了,这个进程就结束了
p.start()
while True:
print("--main()--")
time.sleep(1)
主进程等待子进程先结束
from multiprocessing import Process
import time
def test():
while True:
print("--test--")
time.sleep(1)
p = Process(target=test)
p.start()
#这里主进程不会直接结束,它会等待子进程结束了再结束
Process的init函数
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
给target函数传递参数
args:位置参数元祖
kwargs:关键字参数字典
from multiprocessing import Process
import os
def test(name1,name2):
print("name1=%s,name2=%s"%(name1,name2))
p=Process(target=test,args=("hy","ym"))
p.start()
join阻塞
join([timeout]):等待子进程结束,或等待多少秒(等待时间到了,就不等了)
terminate():不管任务是否完成,立即终止进程
from multiprocessing import Process
import time
def test():
for i in range(5):
print("-%d--"%(i))
time.sleep(1)
p = Process(target=test)
p.start()
p.join()#阻塞,等待子进程结束
print("--main--")
Process子类创建进程
from multiprocessing import Process
import time
class MyProcess(Process):
def run(self):
while True:
print("--1--")
time.sleep(1)
p = MyProcess()
p.start()#当没有给process传递target时,会自动执行run函数
while True:
print("--main--")
time.sleep(1)
对一个不包含target属性的Process类执行start方法,会运行这个类中的run方法。
进程池Pool
当需要创建的子进程数量不多时,可以直接利用multiprocessing中的Process动态生成多个进程。但如果是上百甚至上千个目标,手动的去创建进程的工作量巨大,此时就可以利用multiprocessing模块提供的Pool方法。
初始化Pool时,可以指定一个最大进程数,当有新的请求提交到Pool中时,如果池还没有满,那么就会创建一个新的进程来执行该请求;如果池中的进程数已经达到指定的最大值,那么请求就会等待,直到池中有进程结束,才会创建新的进程来执行。
from multiprocessing import Pool
import time
import os
def Worker(msg):
print("%d,%d进程正在执行"%(msg,os.getpid()))
time.sleep(3)
po=Pool(3)#3表示,进程池最多有3个进程一起执行
for i in range(10):
#向进程添加任务,如果任务超过进程池中进程个数,需要等待,有任务执行完成,会继续执行。
po.apply_async(Worker,(i,))
po.close()#关闭进程池,相当于不能添加新任务了
po.join()#主进程默认不会等待进程池中任务执行完成才推出,所以这里要阻塞,不然主进程结束了,进程池中任务没有执行完成也会跟着结束。
上面的代码在Windows中运行时,需要加一个
if __name__ == "__main__":
不然会报错。
pool中apply阻塞方式
from multiprocessing import Pool
import time
import os
def Worker(msg):
print("%d,%d进程正在执行"%(msg,os.getpid()))
time.sleep(3)
po=Pool(3)
for i in range(10):
print(i)
po.apply(Worker,(i,))#主进程在这里阻塞,等待一个任务的完成
po.close()
po.join()
进程间通信 :
Queue
In [1]: from multiprocessing import Queue
In [2]: q = Queue(3)//队列最大长度为3,只能放三个数据,存放类型随意
In [3]: q.empty()
Out[3]: True
In [4]: q.full()
Out[4]: False
In [5]: q.put("hy")
In [6]: q.put(123)
In [7]: q.get()
Out[7]: 'hy'
In [8]: q.get()
Out[8]: 123
In [9]: q.qsize()
Out[9]: 0
from multiprocessing import Queue,Process
import time
def write(q):
for value in ["A","B","c"]:
print("将数据%s放入队列"%value)
q.put(value)
time.sleep(1)
def read(q):
while True:
if not q.empty():
value=q.get();
print("将数据%s从队列中取出"%value)
time.sleep(1)
else:
break;
if __name__ == "__main__":
q=Queue()#这里没有指明队列长度,表示长度无限
pw = Process(target=write,args=(q,))
pr = Process(target=read,args=(q,))
pw.start()
pw.join()
pr.start()
pr.join()
print("所有数据以及写读完成")
当使用pool时需要用Manager中的Queue
from multiprocessing import Manager,Pool
import os
def write(q):
print("wirte启动(%d),其父进程为(%d)"%(os.getpid(),os.getppid()))
for i in "huangtieniu":
q.put(i)
def read(q):
print("read进程启动(%d),其父进程为(%d)"%(os.getpid(),os.getppid()))
for i in range(q.qsize()):
print("read从进程中获得消息:%s"%q.get())
if __name__ == "__main__":
q = Manager().Queue()
po = Pool()
po.apply(write,(q,))
po.apply(read,(q,))
po.close()
po.join()
print("End")
线程:
Python中thread模块是比较底层的模块,Python中的threading模块是对thread做了一层封装的,可以更加方便的使用。
主线程会等待子线程执行完毕再结束。是为了回收子线程的资源
from threading import Thread
import time
#多个线程执行的是同一个函数,相互之间不影响
def test():
print("I'm so sorry.")
time.sleep(1)
for i in range(5):
t = Thread(target=test)
t.start()
使用Thread子类创建多线程
import threading
import time
class MyThread(threading.Thread):
def run(self):
for i in range(3):
print("I'm %s @ %d"%(self.name,i))
time.sleep(1)
if __name__ == "__main__":
t = MyThread()
t.start()
线程的执行顺序也是不固定的,由操作系统说了算。
import threading
import time
def test1():
for i in range(3):
print("----%d------"%i)
time.sleep(1)
def test2():
for i in range(4,7):
print("-----%d-----"%i)
time.sleep(1)
if __name__ == "__main__":
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
线程共享全局变量,可以利用全局变量通信
from threading import Thread
import time
def work1():
global num
num +=1
print("work1中num=%d"%(num))
def work2():
global num
print("work2中num=%d"%(num))
#线程之间会共享全局变量
num = 100
if __name__ == "__main__":
t1 = Thread(target=work1)
t2 = Thread(target=work2)
t1.start()
time.sleep(1)
t2.start()
线程共享全局变量可能的问题:
from threading import Thread
import time
def test1():
global num
for i in range(1000000):
num += 1
print("--test1--num=%d"%(num))
def test2():
global num
for i in range(1000000):
num += 1
print("--test2--num=%d"%(num))
num = 0
if __name__ == "__main__":
p1 = Thread(target=test1)
p2 = Thread(target=test2)
p1.start()
time.sleep(3)
p2.start()
print("--主线程中num=%d"%(num))
time.sleep(3)这一行注释掉时结果是前一个,加上时结果是后一个。
列表当做实参传递给线程
import threading import Thread
import time
def work1(num):
num.append(44)
print("--in work1--",num)
def work2(num):
time.sleep(1)#保证work1执行完成
print("--in work2--",num)
num = [11,22,33]
if __name__ == "__main__":
t1 = Thread(target=work1,args=(num,))
t2 = Thread(target=work2,args=(num,))
t1.start()
t2.start()
避免全局变量被修改的方式
1.加一个flag标识,轮训
from threading import Thread
import time
def test1():
global num
global flag
if flag == 0:
for i in range(1000000):
num += 1
flag = 1
print("--test1--num=%d"%(num))
def test2():
global num
#轮训,太耗费cpu
while True:
if flag != 0:
for i in range(1000000):
num += 1
break
print("--test2--num=%d"%(num))
num = 0
flag = 0
if __name__ == "__main__":
p1 = Thread(target=test1)
p2 = Thread(target=test2)
p1.start()
#time.sleep(3)
p2.start()
print("--主线程中num=%d"%(num))
避免全局变量被修改---互斥锁
某个线程要更改共享数据时,先将其锁定,此时资源的状态为“锁定”,其他线程不能更改;知道该线程释放资源,将资源的状态变为“非锁定”,其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进行写入操作,从而保证了多线程情况下数据的正确性。
from threading import Thread,Lock
import time
def test1():
global num
#加锁,test1和test2竞争加锁,如果有一方加锁,另一方会阻塞,知道这个所被解开
mutex.acquire()
for i in range(1000000):
num += 1
#解锁
mutex.release()
print("--test1--num=%d"%(num))
def test2():
global num
mutex.acquire()
for i in range(1000000):
num += 1
mutex.release()
print("--test2--num=%d"%(num))
num = 0
flag = 0
#创建一把互斥锁,默认是没有上锁的
mutex = Lock()
if __name__ == "__main__":
p1 = Thread(target=test1)
p2 = Thread(target=test2)
p1.start()
#time.sleep(3)
p2.start()
print("--主线程中num=%d"%(num))
加锁原则:
能不加锁就不加锁,加锁的范围能满足要求就好,不要太大。等待解锁的方式:通知,不是轮训。
多个线程使用非全局变量,非全局变量各自是各自的,不需要加锁
from threading import Thread
import time
import threading
def test1():
name = threading.current_thread().name
print("thread name is %s"%(name))
num = 100
if name == "Thread-1":
num += 1
else:
time.sleep(2)
print("thread is %s,num is %d"%(name,num))
if __name__ == "__main__":
p1 = Thread(target=test1)
p2 = Thread(target=test1)
p1.start()
p2.start()
死锁
在线程间共享多个资源的时候,如果两个线程分别占有一部分资源并且同时等待对方的资源,就会造成死锁。
import time
import threading
from threading import Lock
class MyThread1(threading.Thread):
def run(self):
if mutexA.acquire():
print(self.name+"已对A加锁")
time.sleep(1)
if mutexB.acquire():
print(self.name+"已对B加锁")
mutexB.release()
mutexA.release()
class MyThread2(threading.Thread):
def run(self):
if mutexB.acquire():
print(self.name+"已对B加锁")
time.sleep(1)
if mutexA.acquire():
print(self.name+"已对A加锁")
mutexA.release()
mutexB.release()
mutexA = threading.Lock()
mutexB = threading.Lock()
if __name__ == "__main__":
t1 = MyThread1()
t2 = MyThread2()
t1.start()
t2.start()
相关推荐
- 全网第一个讲清楚CPK如何计算的Step by stepExcel和Python同时实现
-
在网上搜索CPK的计算方法,几乎全是照搬教材的公式,在实际工作做作用不大,甚至误导人。比如这个又比如这个:CPK=min((X-LSL/3s),(USL-X/3s))还有这个,很规范的公式,也很清晰很...
- [R语言] R语言快速入门教程(r语言基础操作)
-
本文主要是为了从零开始学习和理解R语言,简要介绍了该语言的最重要部分,以快速入门。主要参考文章:R-TutorialR语言程序的编写需要安装R或RStudio,通常是在RStudio中键入代码。但是R...
- Python第123题:计算直角三角形底边斜边【PythonTip题库300题】
-
1、编程试题:编写一个程序,找出已知面积和高的直角三角形的另外两边(底边及斜边)。定义函数find_missing_sides(),有两个参数:area(面积)和height(高)。在函数内,计算另外...
- Tensor:Pytorch神经网络界的Numpy
-
TensorTensor,它可以是0维、一维以及多维的数组,你可以将它看作为神经网络界的Numpy,它与Numpy相似,二者可以共享内存,且之间的转换非常方便。但它们也不相同,最大的区别就是Numpy...
- python多进程编程(python多进程进程池)
-
forkwindows中是没有fork函数的,一开始直接在Windows中测试,直接报错importosimporttimeret=os.fork()ifret==0:...
- 原来Python的协程有2种实现方式(python协程模型)
-
什么是协程在Python中,协程(Coroutine)是一种轻量级的并发编程方式,可以通过协作式多任务来实现高效的并发执行。协程是一种特殊的生成器函数,通过使用yield关键字来挂起函数的执行...
- ob混淆加密解密,新版大众点评加密解密
-
1目标:新版大众点评接口参数_token加密解密数据获取:所有教育培训机构联系方式获取难点:objs混淆2打开大众点评网站,点击教育全部,打开页面,切换到mobile模式,才能找到接口。打开开发者工具...
- python并发编程-同步锁(python并发和并行)
-
需要注意的点:1.线程抢的是GIL锁,GIL锁相当于执行权限,拿到执行权限后才能拿到互斥锁Lock,其他线程也可以抢到GIL,但如果发现Lock仍然没有被释放则阻塞,即便是拿到执行权限GIL也要立刻...
- 10分钟学会Python基础知识(python基础讲解)
-
看完本文大概需要8分钟,看完后,仔细看下代码,认真回一下,函数基本知识就OK了。最好还是把代码敲一下。一、函数基础简单地说,一个函数就是一组Python语句的组合,它们可以在程序中运行一次或多次运行。...
- Python最常见的170道面试题全解析答案(二)
-
60.请写一个Python逻辑,计算一个文件中的大写字母数量答:withopen(‘A.txt’)asfs:count=0foriinfs.read():ifi.isupper...
- Python 如何通过 threading 模块实现多线程。
-
先熟悉下相关概念多线程是并发编程的一种方式,多线程在CPU密集型任务中无法充分利用多核性能,但在I/O操作(如文件读写、网络请求)等待期间,线程会释放GIL,此时其他线程可以运行。GIL是P...
- Python的设计模式单例模式(python 单例)
-
单例模式,简单的说就是确保只有一个实例,我们知道,通常情况下类其实可以有很多实例,我们这么来保证唯一呢,全局访问。如配置管理、数据库连接池、日志处理器等。classSingleton: ...
- 更安全的加密工具:bcrypt(bcrypt加密在线)
-
作为程序员在开发工作中经常会使用加密算法,比如,密码、敏感数据等。初学者经常使用md5等方式对数据进行加密,但是作为严谨开发的程序员,需要掌握一些相对安全的加密方式,今天给大家介绍下我我在工作中使用到...
- 一篇文章搞懂Python协程(python协程用法)
-
前引之前我们学习了线程、进程的概念,了解了在操作系统中进程是资源分配的最小单位,线程是CPU调度的最小单位。按道理来说我们已经算是把cpu的利用率提高很多了。但是我们知道无论是创建多进程还是创建多线...
- Python开发必会的5个线程安全技巧
-
点赞、收藏、加关注,下次找我不迷路一、啥是线程安全?假设你开了一家包子铺,店里有个公共的蒸笼,里面放着刚蒸好的包子。现在有三个顾客同时来拿包子,要是每个人都随便伸手去拿,会不会出现混乱?比如第一个顾...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)