一、线程、进程
建议进程池,可以更好地控制进程数量
进程是资源分配的基本单位。
线程是任务调度和分配的基本单位。
- 打印线程 id:
- threading.currentThread() # type 是 %s
- <TestThread(Thread-1, started 1106852192)>
- threading.currentThread().ident # type 是 %d
- 1106852192
- threading.currentThread() # type 是 %s
- 打印进程 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()