手把手带你了解python多进程,多线程
作者:Mr DaYang 发布时间:2021-07-16 02:08:42
标签:python,多进程,多线程
说明
相应的学习视频见链接,本文只对重点进行总结。
多进程
重点(只要看下面代码的main函数即可)
1.创建
2.如何开守护进程
3.多进程,开销大,用for循环调用多个进程时,后台cpu一下就上去了
import time
import multiprocessing
import os
def dance(who,num):
print("dance父进程:{}".format(os.getppid()))
for i in range(1,num+1):
print("进行编号:{}————{}跳舞。。。{}".format(os.getpid(),who,i))
time.sleep(0.5)
def sing(num):
print("sing父进程:{}".format(os.getppid()))
for i in range(1,num+1):
print("进行编号:{}----唱歌。。。{}".format(os.getpid(),i))
time.sleep(0.5)
def work():
for i in range(10):
print("工作中。。。")
time.sleep(0.2)
if __name__ == '__main__':
# print("main主进程{}".format(os.getpid()))
start= time.time()
#1 进程的创建与启动
# # 1.1创建进程对象,注意dance不能加括号
# # dance_process = multiprocessing.Process(target=dance)#1.无参数
# dance_process=multiprocessing.Process(target=dance,args=("lin",3))#2.以args=元祖方式
# sing_process = multiprocessing.Process(target=sing,kwargs={"num":3})#3.以kwargs={}字典方式
# # 1.2启动进程
# dance_process.start()
# sing_process.start()
#2.默认-主进程和子进程是分开的,主进程只要1s就可以完成,子进程要2s,主进程会等所有子进程执行完,再退出
# 2.1子守护主进程,当主一但完成,子就断开(如qq一关闭,所有聊天窗口就没了).daemon=True
work_process = multiprocessing.Process(target=work,daemon=True)
work_process.start()
time.sleep(1)
print("主进程完成了!")#主进程和子进程是分开的,主进程只要1s就可以完成,子进程要2s,主进程会等所有子进程执行完,再退出
print("main主进程花费时长:",time.time()-start)
#
多线程
重点
1.创建
2.守护线程
3.线程安全问题(多人抢票,会抢到同一张)
import time
import os
import threading
def dance(num):
for i in range(num):
print("进程编号:{},线程编号:{}————跳舞。。。".format(os.getpid(),threading.current_thread()))
time.sleep(1)
def sing(count):
for i in range(count):
print("进程编号:{},线程编号:{}----唱歌。。。".format(os.getpid(),threading.current_thread()))
time.sleep(1)
def task():
time.sleep(1)
thread=threading.current_thread()
print(thread)
if __name__ == '__main__':
# start=time.time()
# # sing_thread =threading.Thread(target=dance,args=(3,),daemon=True)#设置成守护主线程
# sing_thread = threading.Thread(target=dance, args=(3,))
# dance_thread = threading.Thread(target=sing,kwargs={"count":3})
#
# sing_thread.start()
# dance_thread.start()
#
# time.sleep(1)
# print("进程编号:{}主线程结束...用时{}".format(os.getpid(),(time.time()-start)))
for i in range(10):#多线程之间执行是无序的,由cpu调度
sub_thread = threading.Thread(target=task)
sub_thread.start()
线程安全
由于线程直接是无序进行的,且他们共享同一个进程的全部资源,所以会产生线程安全问题(比如多人在线抢票,买到同一张)
#下面代码在没有lock锁时,会卖出0票,加上lock就正常
import threading
import time
lock =threading.Lock()
class Sum_tickets:
def __init__(self,tickets):
self.tickets=tickets
def window(sum_tickets):
while True:
with lock:
if sum_tickets.tickets>0:
time.sleep(0.2)
print(threading.current_thread().name,"取票{}".format(sum_tickets.tickets))
sum_tickets.tickets-=1
else:
break
if __name__ == '__main__':
sum_tickets=Sum_tickets(10)
sub_thread1 = threading.Thread(name="窗口1",target=window,args=(sum_tickets,))
sub_thread2 = threading.Thread(name="窗口2",target=window,args=(sum_tickets,))
sub_thread1.start()
sub_thread2.start()
高并发拷贝(多进程,多线程)
import os
import multiprocessing
import threading
import time
def copy_file(file_name,source_dir,dest_dir):
source_path = source_dir+"/"+file_name
dest_path =dest_dir+"/"+file_name
print("当前进程为:{}".format(os.getpid()))
with open(source_path,"rb") as source_file:
with open(dest_path,"wb") as dest_file:
while True:
data=source_file.read(1024)
if data:
dest_file.write(data)
else:
break
pass
if __name__ == '__main__':
source_dir=r'C:\Users\Administrator\Desktop\注意力'
dest_dir=r'C:\Users\Administrator\Desktop\test'
start = time.time()
try:
os.mkdir(dest_dir)
except:
print("目标文件已存在")
file_list =os.listdir(source_dir)
count=0
#1多进程
for file_name in file_list:
count+=1
print(count)
sub_processor=multiprocessing.Process(target=copy_file,
args=(file_name,source_dir,dest_dir))
sub_processor.start()
# time.sleep(20)
print(time.time()-start)
#这里有主进程和子进程,通过打印可以看出,主进程在创建1,2,3,4,,,21过程中,子进程已有的开始执行,也就是说,每个进程是互不影响的
# 9
# 10
# 11
# 12
# 13
# 当前进程为:2936(当主进程创建第13个时,此时,第一个子进程开始工作)
# 14
# 当前进程为:10120
# 当前进程为:10440
# 15
# 当前进程为:9508
# 2多线程
# for file_name in file_list:
# count += 1
# print(count)
# sub_thread = threading.Thread(target=copy_file,
# args=(file_name, source_dir, dest_dir))
# sub_thread.start()
# # time.sleep(20)
# print(time.time() - start)
来源:https://blog.csdn.net/m0_46204224/article/details/119737937


猜你喜欢
- 前言本文主要给大家介绍了关于Yii2结合Workerman的websocket的相关内容,两者都是好东西,我就想着能不能结合起来,这样Yii
- 锁定数据库的一个表SELECT * FROM table WITH (HOLDLOCK)注意: 锁定数据库的一个表的区别SELECT * F
- python3 manage.py makemigrations # 生成数据库迁移文件python3 manage.py migrate
- 1. 引言Python是一种强大的编程语言,有很多内置的功能来处理文本。然而,有时候,我们需要处理的文本非常复杂,而Python内置的功能可
- Numba是Python的即时编译器,在使用NumPy数组和函数以及循环的代码上效果最佳。使用Numba的最常见方法是通过其装饰器集合,这些
- keras 深度学习框架中get_value函数运行越来越慢,内存消耗越来越大问题问题描述如上图所示,经过时间和内存消耗跟踪测试,发现是ke
- 本文分为两个部分,第一部分是关于pip,第二部分关于pygal,主要关于二者的简介以及安装过程的分享,希望对大家有所帮助。一、pip1.简介
- 本文实例讲述了Python学习笔记之字符串和字符串方法。分享给大家供大家参考,具体如下:字符串在 python 中,字符串的变量类型显示为
- oblog 推出了4.0的最新版本,这个不是重点,重点是4.0的版本中附带了xml-rpc支持。oblog的支持代表着大量的国内blog站点
- 矩阵增加行np.row_stack() 与 np.column_stack()import numpy as npa = np.array(
- 如果PyPi上搜html2text的话,找到的是另外一个库:Alir3z4/html2text。这个库是从aaronsw/html2text
- 这篇文章主要介绍了python智联招聘爬虫并导入到excel代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
- 1. 首先 进入cmd, 输入python,看python是否安装成功说明python安装,没有问题2. 修改注册表第一步window +
- 本文实例讲述了PHP队列用法。分享给大家供大家参考。具体分析如下:什么是队列,是先进先出的线性表,在具体应用中通常用链表或者数组来实现,队列
- 安装Pycharm进行Python开发时,经常右下角提示No R interpreter defined,处理方式:1、安装R,然后将R的路
- 本文实例为大家分享了python实现txt文件格式转换为arff格式的具体代码,供大家参考,具体内容如下将文件读取出来的时候默认都是字符型的
- 一、异步解决方案的进化史JavaScript的异步操作一直是个麻烦事,所以不断有人提出它的各种解决方案。可以追溯到最早的回调函数(ajax老
- Mysqli是php5之后才有的功能,没有开启扩展的朋友可以打开您的php.ini的配置文件。 查找下面的语句:;extension=php
- 1、生成了身份证前六位地区码对照表JSON文件2、python 读取JSON文件提取码【3297】 json文件下载废话不多说,先上效果图一
- Python实现模拟时钟代码推荐# coding=utf8import sys, pygame, math, randomfrom pyga