首页 > 系统相关 >Python笔记-多进程多线程

Python笔记-多进程多线程

时间:2022-12-03 10:05:30浏览次数:42  
标签:11 26 20 Python begin2022 笔记 41 ------ 多线程


日常运维中,经常需要并发来提升工作效率。Python提供了多线程和多进程两种方式。

import time
import threading
import multiprocessing

def print_fun(num):
print(time.strftime('%Y-%m-%d %H:%M:%S'),num,"begin")
time.sleep(2)
print(time.strftime('%Y-%m-%d %H:%M:%S'),num,"------end")


def mutil_thread():
print("\n多线程模式")
threads = []
for i in range(5):
num = str(i)
t = threading.Thread(target=print_fun,args=(num))
threads.append(t)

for x in threads:
x.start()
for x in threads:
x.join()

def mutil_process():
print("\n多进程模式")
threads = []
for i in range(5):
num = str(i)
t = multiprocessing.Process(target=print_fun,args=(num))
threads.append(t)

for x in threads:
x.start()
for x in threads:
x.join()

if __name__ == '__main__':
mutil_thread()
mutil_process()
[root@test1 dataC]# python3 test.py 

多线程模式
2022-11-26 20:41:17 0 begin
2022-11-26 20:41:17 1 begin
2022-11-26 20:41:17 3 begin
2022-11-26 20:41:17 2 begin
2022-11-26 20:41:17 4 begin
2022-11-26 20:41:19 0 ------end
2022-11-26 20:41:19 2 ------end
2022-11-26 20:41:19 4 ------end
2022-11-26 20:41:19 3 ------end
2022-11-26 20:41:19 1 ------end

多进程模式
2022-11-26 20:41:19 0 begin
2022-11-26 20:41:19 3 begin
2022-11-26 20:41:19 1 begin
2022-11-26 20:41:19 4 begin
2022-11-26 20:41:19 2 begin
2022-11-26 20:41:21 0 ------end
2022-11-26 20:41:21 3 ------end
2022-11-26 20:41:21 1 ------end
2022-11-26 20:41:21 2 ------end
2022-11-26 20:41:21 4 ------end


标签:11,26,20,Python,begin2022,笔记,41,------,多线程
From: https://blog.51cto.com/dbadadong/5908460

相关文章

  • Python笔记-脚本参数传递
    编写Python脚本,经常需要从外部传递参数,此时需要用到getopt和sys。语法如下:getopt.getopt(args,shortopts,longopts=[])args参数列表shortopts短参数,如:-hlongopt......
  • Python笔记-Python2和Python3兼容
    Python2与Python3在很数据类型、语法上面都有很大区别。为保证编写的脚本在Python2和Python3下兼容,需要在代码中做版本判断。示例代码如下:importsyspversion=int(s......
  • Python笔记-从配置读取参数
    实用的脚步通常需要一些动态参数,如果参数太多,从命令行传递就太麻烦了。从配置文件读取,是比较实用的方法。以下示例为从test.cfg中读取参数,配置文件为json格式。配置文件......
  • Python 让图像变卡通图
    ✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。......
  • python解析yaml文件
    1、初始化yaml文件的目录def__init__(self):self.yaml_root_path='D:\\Code\\PythonProject\\UIAutoProject\\config\\yaml\\'2、读取yaml文件的方法defread_......
  • 【学习笔记】计算几何(总)
    计算几何入门1计算几何入门2......
  • Python遍历某个文件夹下的所有文件夹,每个文件夹只保留最新7个文件
    importosroot=r"D:\_back"fordirpath,dirnames,filenamesinos.walk(root):fordirnameindirnames:_dir=os.path.join(dirpath,dirname)......
  • Python实验报告——第13章 Pygame游戏编程
    实验报告实例01:制作一个跳跃的小球游戏代码如下:importsysimportpygamepygame.init()size=width,height=640,480screem=pygame.display.set_mode(size)c......
  • python 高阶函数
    高阶函数(High-orderFunction)​ 数学概念y=f(g(x))​ 在数学和计算机科学中,高阶函数应当是至少满足下面一个条件的函数​ 接受一个或多个函数作为参数​ 输......
  • python 装饰器
    defadd(x,y):returnx+ydeflogger(fn):defwrapper(*args,**kwargs):print('调用前增强')ret=fn(*args,**kwargs)#参数解构......