Python 进程和设计模式

本文介绍了Python中线程和进程的概念及其使用,包括进程池的实现,以及展示了单例模式的三种实现方式:饿汉式、懒汉式和线程安全的懒汉式。通过实例代码详细阐述了如何在多线程环境下确保单例的正确创建和使用。
摘要由CSDN通过智能技术生成

一、线程、进程

建议进程池,可以更好地控制进程数量

进程是资源分配的基本单位。

线程是任务调度和分配的基本单位。

  • 打印线程 id:
    • threading.currentThread()  # type 是 %s
      • <TestThread(Thread-1, started 1106852192)>
    • threading.currentThread().ident  # type 是 %d
      • 1106852192
  • 打印进程 id :
    • 当前进程:os.getpid(%s)
    • 父进程:os.getppid(%d)

1. 线程

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import multiprocessing
import time
import os


def run(process_name):
    print('process { %s } PID { %s }, parent process ID { %s }, start time { %s }'
        % (process_name, os.getpid(), os.getppid(), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
    time.sleep(1)
    print('process { %s } PID { %s }, end time { %s }'
        % (process_name, os.getpid(), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))

def main():
    threads = []
    for i in range(0, 3):
        p_test = multiprocessing.Process(target=run, args=("Process - " + str(i), ))
        p_test.start()
        threads.append(p_test)

    for thread in threads:
        thread.join()


if __name__ == "__main__":
    main()

2. 进程 

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import threading
import time
import os


class TestThread(threading.Thread):
    def __init__(self, process_name):
        super(TestThread, self).__init__()
        self.process_name = process_name

    def run(self):
        print('process { %s } PID { %s }, parent process ID { %s }, start time { %s }'
            % (self.process_name, os.getpid(), os.getppid(), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
        time.sleep(1)
        print('process { %s } PID { %s }, end time { %s }'
            % (self.process_name, os.getpid(), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))

def main():
    threads = []
    for i in range(0, 3):
        p_test = TestThread("Process - " + str(i))
        p_test.start()
        threads.append(p_test)

    for thread in threads:
        thread.join()


if __name__ == "__main__":
    main()

3. 进程池 

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import multiprocessing
import time
import os


def run(process_name):
    print('process { %s } PID { %s }, parent process ID { %s }, start time { %s }'
        % (process_name, os.getpid(), os.getppid(), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
    time.sleep(1)
    print('process { %s } PID { %s }, end time { %s }'
        % (process_name, os.getpid(), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))

def main():
    pool = multiprocessing.Pool(processes=2)
    for i in range(0, 3):
        return_result = pool.apply_async(run, args=("Process - " + str(i), ))

    pool.close()
    pool.join()


if __name__ == "__main__":
    main()

4、进程间通信

  • 管道
  • 消息队列
  • 共享内存
  • Semaphore

二、单例模式:

1. 饿汉式(线程安全)

  • __new__() 是由 object 基类提供的内置静态方法;
  • 在通过类名来创建对象的时候,python 的解释器解释器会首先调用 __new__() 分配空间并获得对象的引用;
  • 然后,将引用作为第一个参数传递给 __init__() 方法。
import threading


class HungrySingleton(object):
    def __init__(self):
        if not self._instance:
            print('调用__init__, 实例未创建')
        else:
            print('调用__init__,实例已经创建过了:', self._instance)

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            HungrySingleton._instance = super().__new__(cls)
        return HungrySingleton._instance


def task(arg):
    obj = HungrySingleton()
    print("obj : {obj} \n".format(obj=obj))


for i in range(3):
    t = threading.Thread(target=task, args=[i, ])
    t.start()

2. 懒汉式(线程不安全)

import threading


class LazySingleton(object):
    __instance = None

    def __init__(self):
        if not LazySingleton.__instance:
            print('调用__init__, 实例未创建')
        else:
            print('调用__init__,实例已经创建过了:', LazySingleton.__instance)

    @classmethod
    def get_instance(cls):
        if not cls.__instance:
            cls.__instance = LazySingleton()

        return cls.__instance


def task(arg):
    obj = LazySingleton().get_instance()
    print("obj : {obj} \n".format(obj=obj))


for i in range(3):
    t = threading.Thread(target=task, args=[i, ])
    t.start()

运行结果:

3. 线程安全懒汉式

import threading


class LazySingleton(object):
    __instance = None
    _instance_lock = threading.Lock()

    def __init__(self):
        if not LazySingleton.__instance:
            print('调用__init__, 实例未创建')
        else:
            print('调用__init__,实例已经创建过了:', LazySingleton.__instance)

    @classmethod
    def get_instance(cls):
        if not cls.__instance:
            with LazySingleton._instance_lock:
                if not cls.__instance:
                    cls.__instance = LazySingleton()

        return cls.__instance


def task(arg):
    obj = LazySingleton().get_instance()
    print("obj : {obj} \n".format(obj=obj))


for i in range(3):
    t = threading.Thread(target=task, args=[i, ])
    t.start()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值