栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python多进程和多线程

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python多进程和多线程

前言

进程是资源分配的最小单位,线程是CPU调度的最小单位

进程:操作系统的每个一个程序都是一个进程
线程:进程包括了线程,一个进程下可以有多个线程同时进行

一、多进程

代码如下(示例):

# -*- coding: utf-8 -*-
"""
@Time : 2022/5/20 13:20
@Author : 盘盘
@File :more_process.py
@IDE :PyCharm

"""
from random import randint
from time import time
from multiprocessing import Process

def open(url):
    print("打开博客:%s" % url)
    time = randint(1,10)
    print("打开博客:%s,耗时:%d秒" % (url, time))

def process_run():
    start = time()
    pro1 = Process(target=open,args=("https://blog.csdn.net/weixin_44688529?spm=1010.2135.3001.5343",))
    p1.start()
    p2 = Process(target=open, args=("https://www.baidu.com/",))
    p2.start()
    p1.join()
    p2.join()
    end = time()
    print('总共耗费了%.2f秒.' % (end - start))

if __name__ == '__main__':
    process_run()
二、多线程

代码如下(示例):

# -*- coding: utf-8 -*-
"""
@Time : 2022/5/20 13:28
@Author : 盘盘
@File :more_thread.py
@IDE :PyCharm

"""
from random import randint
from threading import Thread
from time import time

def open(url):
    print("打开博客:%s" % url)
    time = randint(1,10)
    print("打开博客:%s,耗时:%d秒" % (url, time))

def thread_run():
    start = time()
    t1 = Thread(target=open,args=("https://blog.csdn.net/weixin_44688529?spm=1010.2135.3001.5343",))
    t1.start()
    t2 = Thread(target=open, args=("https://www.baidu.com/",))
    t2.start()
    t1.join()
    t2.join()
    end = time()
    print('总共耗费了%.2f秒.' % (end - start))

if __name__ == '__main__':
    thread_run()
总结

线程执行开销小,但不利于资源的管理和保护,而进程正相反。而且同一进程多个线程之间是数据共享的,多个进程之间数据相互独立,但是可以采取一些方式进行信息交互(比如队列)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/918035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号