进程&&线程

print('Process (%s) start...' % os.getpid())
# Only works on Unix/Linux/Mac:
pid = os.fork()
if pid == 0:
    #子进程
    print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))
else:
    print('I (%s) just created a child process (%s).' % (os.getpid(), pid))
    
# Process (28301) start...
# I (28301) just created a child process (28302).
# I am child process (28302) and my parent is 28301.

multiprocessing(多进程)

因为在windows是没有fork调用的,所以为了跨平台支持,可以使用multiprocessing跨平台的多进程模块
multiprocessing模块提供了一个Process类来代表一个进程对象


from multiprocessing import Process
import os

def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid()))

print("parent process %s" % os.getpid())
p=Process(target=run_proc, args=("test",)) #创建子进程
print("child process will start")  
p.start()# 启动子进程
p.join() # 等待子进程结束后继续运行
print("child process end")

# parent process 28492
# child process will start
# Run child process test (28493)...
# child process end

join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。

Pool(进程池)

from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(4) #设置同事可以执行4个进程
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close() # 调用close()之后就不能继续添加新的Process了
    p.join()  # 对Pool对象调用join()会等待所有子进程执行完毕,在
    print('All subprocesses done.')

subprocess 子进程

subprocess模块 允许我们创建子进程,连接其输入、输出、错误通道

import subprocess

print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org'])
# 相当于在命令行执行  nslookup www.python.org
print('Exit code:', r)


# 子进程还需要输入,则可以通过communicate()方法输入:
import subprocess

print('$ nslookup')
p = subprocess.Popen(['nslookup'], stdin=·, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate(b'set q=mx\npython.org\nexit\n')
print(output.decode('utf-8'))
print('Exit code:', p.returncode)

进程间通信

进程间通信,可以通过mutiprocessing提供的Queuepipes等方式交换数据

# 一个queue 可以往里 读写数据 实现数据交换共享

from multiprocessing import Process, Queue
import os, time, random

# 写数据进程执行的代码:
def write(q):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)

if __name__=='__main__':
    # 父进程创建Queue,并传给各个子进程:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw,写入:
    pw.start()
    # 启动子进程pr,读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环,无法等待其结束,只能强行终止:
    pr.terminate()

父进程所有Python对象都必须通过pickle序列化再传到子进程去

多线程

我们通常使用threading模块操作线程

启动线程: 就是将要执行的任务任务函数传入创建Thread实例,然后start()开始执行

import time, threading

# 新线程执行的代码:
def loop():
    print('thread %s is running...' % threading.current_thread().name)
    n = 0
    while n < 5:
        n = n + 1
        print('thread %s >>> %s' % (threading.current_thread().name, n))
        time.sleep(1)
    print('thread %s ended.' % threading.current_thread().name)

print('thread %s is running...' % threading.current_thread().name)
#
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)

Pythonthreading模块有个current_thread()函数,它永远返回当前线程的实例。主线程实例的名字叫MainThread,子线程的名字在创建时指定,我们用LoopThread命名子线程。名字仅仅在打印时用来显示,完全没有其他意义,如果不起名字Python就自动给线程命名为Thread-1,Thread-2

Lock

避免多线程对数据读写的冲突,需要lock

balance = 0
lock = threading.Lock()

def run_thread(n):
    for i in range(100000):
        # 先要获取锁:
        lock.acquire() #当有多个线程执行时,只有一个县城能成功获取锁
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release()

多核问题

Python由于历史遗留问题,同一进程的不同线程其实只能用到一个cpu核,即使启动了多个线程

Python的线程虽然是真正的线程,但解释器执行代码时,有一个GIL锁:Global Interpreter Lock,任何Python线程执行前,必须先获得GIL锁,然后,每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行。这个GIL全局锁实际上把所有线程的执行代码都给上了锁,所以,多线程在Python中只能交替执行,即使100个线程跑在100核CPU上,也只能用到1个核。

Python虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个Python进程有各自独立的GIL锁,互不影响。

ThreadLocal

多线程中,为不同线程绑定不同数据时,可以使用ThreadLocal

import threading

# 创建全局ThreadLocal对象:
local_school = threading.local()

def process_student():
    # 获取当前线程关联的student:
    std = local_school.student
    print('Hello, %s (in %s)' % (std, threading.current_thread().name))

def process_thread(name):
    # 绑定ThreadLocal的student:
    local_school.student = name
    process_student()

t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()

每个线程可以读写ThreadLocal对象的属性,但是互不影响,只操作自己线程对应值,互不干扰,也不用管理锁的问题

一个ThreadLocal变量虽然是全局变量,但每个线程都只能读写自己线程的独立副本,互不干扰。ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题。

分布式进程

ThreadProcess中应该优先选择Process,因为其更稳定,而且可以分布到多台机器上,而Thread只能分不到同一台机器的多个CPU上

mutiprocessing的子模块manager支持把多进程分布到多台机器

一个服务进程可以作为调度者,将任务分布到其他多个进程中,依靠网络通信。由于managers模块封装很好,不必了解网络通信的细节,就可以很容易地编写分布式多进程程序。