百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

网络编程 04:进程与线程的补充 程序进程线程三者的关系

suiw9 2024-10-23 18:50 25 浏览 0 评论

一.多任务运行控制

1 . 等待子任务结束(join)

进程或者线程添加 join 方法之后,会等待子任务结束,如果没有结束则会阻塞,直到子任务结束,因此join一般都是放在程序的最后面,通过阻塞进行等待。(进程与线程都可使用)

import time
import multiprocessing

def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    print(x+y)
    time.sleep(5)
    print('func-end', new_time())

if __name__ == '__main__':
    print('main-start',new_time())

    p1 = multiprocessing.Process(target = func,args=(1,2)) # 实例化一个新的子进程
    p1.start()

    time.sleep(5)

    p1.join()  # 等待子进程结束
    
print('main-end',new_time())

主进程的模拟耗时操作与子进程同时运行,但因子进程需要多运行一部 x + y ,以至于子进程结束时间要迟于主进程结束时间。


但因加入了 join 方法,主进程只会在子进程运行结束后才会结束。( main 是主进程,func 是子进程)


2.获取当前进程

在进程内容获取当前进程,方便查找问题(进程与线程都可使用)

import time
import multiprocessing

def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    print(multiprocessing.current_process()) # 获取当前运行的进程对象
    print(x+y)
    time.sleep(5)
    print('func-end', new_time())

if __name__ == '__main__':
    print(multiprocessing.current_process()) # 获取当前运行的进程对象

    print('main-start',new_time())

    p1 = multiprocessing.Process(target = func,args=(1,2)) # 实例化一个新的子进程
    p1.start()

    time.sleep(5) # 模拟耗时操作,主进程的任务

    p1.join()  # 等待子进程结束,主要是通过阻塞的方式来等待

print('main-end',new_time())


MainProcess 表示主进程,Process - 1 表示子进程。

3.任务名字

import time
import multiprocessing

def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    print(x+y)
    time.sleep(5)
    print('func-end', new_time())

if __name__ == '__main__':
	print('main-start',new_time())
	
	p1 = multiprocessing.Process(target = func,args=(1,2)) # 实例化一个新的子进程
    p1.name = '进程一号' # 获取进程名
    print(p1.name) # 修改属性名,改变进程名
    p1.start()

    time.sleep(5) # 模拟耗时操作,主进程的任务

    p1.join()  # 等待子进程结束,主要是通过阻塞的方式来等待

print('main-end',new_time())


4.终止进程

在正常情况下,主进程的结束,并不会影响子进程,但是也可以在主进程结束之后,强制终止子进程。(注意线程不能终止,只能等待结束)

import time
import multiprocessing

def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    # print(multiprocessing.current_process()) # 获取当前运行的进程对象
    print(x+y)
    time.sleep(5)
    print('func-end', new_time())

if __name__ == '__main__':
    # print(multiprocessing.current_process()) # 获取当前运行的进程对象

    print('main-start',new_time())

    p1 = multiprocessing.Process(target = func,args=(1,2)) # 实例化一个新的子进程
    # p1.name = '进程一号' # 获取进程名
    # print(p1.name) # 修改属性名,改变进程名
    p1.start()

    time.sleep(5) # 模拟耗时操作,主进程的任务

    # p1.join()  # 等待子进程结束,主要是通过阻塞的方式来等待

    p1.terminate()

print('main-end',new_time())

二.多任务标识

1.进程(PID)

在Linux中,只要进程一创建,系统就会分配一个pid,在程序运行过程中,pid都不会改变。可以通过pid查看进程对资源的使用情况,也可以通过PID来控制进程的运行。( pid 一般是在 start()方法后执行的)

import time
import multiprocessing

def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    # print(multiprocessing.current_process()) # 获取当前运行的进程对象
    print(x+y)
    time.sleep(500)
    print('func-end', new_time())

if __name__ == '__main__':
    # print(multiprocessing.current_process()) # 获取当前运行的进程对象

    print('main-start',new_time())

    p1 = multiprocessing.Process(target = func,args=(1,2)) # 实例化一个新的子进程
    print('beform start',p1.pid)
    # p1.name = '进程一号' # 获取进程名
    # print(p1.name) # 修改属性名,改变进程名

    p1.start()
    print('after start',p1.pid)

    time.sleep(5) # 模拟耗时操作,主进程的任务

    # p1.join()  # 等待子进程结束,主要是通过阻塞的方式来等待

    # p1.terminate()

print('main-end',new_time())

可以利用程序的 pid 对程序进行操作,例如使用远程连接工具杀死进程


2.线程(ident)

线程还是在一个进程当中,因此不会有PID。线程由python解释器调度,为了调度方便,会有ident,类似于操作系统中的pid。( ident 一般也是在 start()方法后执行的)

import time
import threading


def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    print(x+y)
    time.sleep(5)
    print('func-end', new_time())

print('main-start',new_time())

t1 = threading.Thread(target=func,args=(1,2))
print('befor start',t1.ident)
t1.start()
print('after start',t1.ident)

time.sleep(5)
print('main-end',new_time())


3.生命周期(is_alive())

进程的生命周期开始于 start,实例化之后,进程并没有启动,只有启动之后才开始生命周期。

import time
import multiprocessing

def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    # print(multiprocessing.current_process()) # 获取当前运行的进程对象
    print(x+y)
    time.sleep(3)
    print('func-end', new_time())

if __name__ == '__main__':
    # print(multiprocessing.current_process()) # 获取当前运行的进程对象

    # print('main-start',new_time())

    p1 = multiprocessing.Process(target = func,args=(1,2)) # 实例化一个新的子进程
    # print('befor start',p1.pid)
    # p1.name = '进程一号' # 获取进程名
    # print(p1.name) # 修改属性名,改变进程名

    print('befor start',p1.is_alive())
    p1.start()
    print('after start', p1.is_alive())
    # print('after start',p1.pid)

    time.sleep(3) # 模拟耗时操作,主进程的任务

    p1.join()  # 等待子进程结束,主要是通过阻塞的方式来等待
    print('join start', p1.is_alive())

    # p1.terminate()

print('main-end',new_time())

三.守护模式

开启守护模式之后,主进程结束,子进程会自动结束,但前提是每个子进程都需要开启守护模式。只需在实例化子进程时将 daemon 设置为 True。

import time
import multiprocessing


def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

def func(x,y):
    print('func-start', new_time())
    print(x+y)
    time.sleep(5)
    print('func-end', new_time())

if __name__ == '__main__':
    print('main-start',new_time())


    p1 = multiprocessing.Process(target = func,args=(1,2),daemon=True) # 实例化一个新的子进程
    p1.start()

    time.sleep(5)
    print('main-end',new_time())

四.面对对象编程

利用多进程实现 redis 数据库的并发

import time
import redis
import multiprocessing

"""
自定义一个进程类
    通过class关键字定一个类(普通的类)
    如果你想要有进程对象的功能以及属性,做继承
    
    继承于进程类(自定义继承类)

"""

def new_time():
    """
    返回asc格式的当前时间
    :return:
    """
    return time.asctime(time.localtime(time.time()))

class RedisProcess(multiprocessing.Process):
    def __init__(self,db,key,values):
        super().__init__()
        self.connect = redis.StrictRedis(db=db) # 连接redis
        self.key = key
        self.values = values

    def set(self):
        """
        插入数据 设置 key和 value
        :return:
        """
        self.connect.set(self.key,self.values)

    def get(self):
        return self.connect.get(self.key)

    def run(self):
        """
        start 方法会自动调用run方法
        start 后,就插入数据,并返回插入的值
        重写run
        :return:
        """
        print('inner-start',new_time())
        print(multiprocessing.current_process)
        self.set()

        print(self.get().decode('utf-8'))
        time.sleep(1) #  模拟耗时操作
        print('inner-end',new_time())

print('outer-start',new_time())
r1 = RedisProcess(1,'yige','18') # 实例化自定义进程类(创建进程,连接redis)
r2 = RedisProcess(2,'liangge','18')

r1.start() # start会自动调用run
r2.start()
print('outer-end',new_time())

附(今日份学习):

多任务控制:



守护模式:


利用多进程操作 redis 数据库实现并发:



相关推荐

5款Syslog集中系统日志常用工具对比推荐

一、为何要集中管理Syslog?Syslog由Linux/Unix系统及其他网络设备生成,广泛分布于整个网络。因其包含关键信息,可用于识别网络中的恶意活动,所以必须对其进行持续监控。将Sys...

跨平台、多数据库支持的开源数据库管理工具——DBeaver

简介今天给大家推荐一个开源的数据库管理工具——DBeaver。它支持多种数据库系统,包括Mysql、Oracle、PostgreSQL、SLQLite、SQLServer等。DBeaver的界面友好...

强烈推荐!数据库管理工具:Navicat Premium 16.3.2 (64位)

NavicatPremium,一款集数据迁移、数据库管理、SQL/查询编辑、智能设计、高效协作于一体的全能数据库开发工具。无论你是MySQL、MariaDB、MongoDB、SQLServer、O...

3 年 Java 程序员还玩不转 MongoDB,网友:失望

一、什么场景使用MongoDB?...

拯救MongoDB管理员的GUI工具大赏:从菜鸟到极客的生存指南

作为一名在NoSQL丛林中披荆斩棘的数据猎人,没有比GUI工具更称手的瑞士军刀了。本文将带你围观五款主流MongoDB管理神器的特性与暗坑,附赠精准到扎心的吐槽指南一、MongoDBCompass:...

mongodb/redis/neo4j 如何自己打造一个 web 数据库可视化客户端?

前言最近在做neo4j相关的同步处理,因为产线的可视化工具短暂不可用,发现写起来各种脚本非常麻烦。...

solidworks使用心得,纯干货!建议大家收藏

SolidWorks常见问题...

统一规约-关乎数字化的真正实现(规范统一性)

尽管数字化转型的浪潮如此深入人心,但是,对于OPCUA和TSN的了解却又甚少,这难免让人质疑其可实现性,因为,如果缺乏统一的语义互操作规范,以及更为具有广泛适用的网络与通信,则数字化实际上几乎难以具...

Elasticsearch节点角色配置详解(Node)

本篇文章将介绍如下内容:节点角色简介...

产前母婴用品分享 篇一:我的母婴购物清单及单品推荐

作者:DaisyH8746在张大妈上已经混迹很久了,有事没事看看“什么值得买”已渐渐成了一种生活习惯,然而却从来没有想过自己要写篇文章发布上来,直到由于我产前功课做得“太过认真”(认真到都有点过了,...

比任何人都光彩照人的假期!水润、紧致的肌肤护理程序

图片来源:谜尚愉快的假期临近了。身心振奋的休假季节。但是不能因为这种心情而失去珍贵的东西,那就是皮肤健康。炙热的阳光和强烈的紫外线是使我们皮肤老化的主犯。因此,如果怀着快乐的心情对皮肤置之不理,就会使...

Arm发布Armv9边缘AI计算平台,支持运行超10亿参数端侧AI模型

中关村在线2月27日消息,Arm正式发布Armv9边缘人工智能(AI)计算平台。据悉,该平台以全新的ArmCortex-A320CPU和领先的边缘AI加速器ArmEthos-U85NPU为核心...

柔性——面向大规模定制生产的数字化实现的基本特征

大规模定制生产模式的核心是柔性,尤其是体现在其对定制的要求方面。既然是定制,并且是大规模的定制,对于制造系统的柔性以及借助于数字化手段实现的柔性,就提出了更高的要求。面向大规模定制生产的数字化业务管控...

创建PLC内部标准——企业前进的道路

作者:FrankBurger...

标准化编程之 ----------- 西门子LPMLV30测试总结

PackML乃是由OMAC开发且被ISA所采用的自动化标准TR88.00.02,能够更为便捷地传输与检索一致的机器数据。PackML的主要宗旨在于于整个工厂车间倡导通用的“外观和感觉”,...

取消回复欢迎 发表评论: