第十章-进程和线程

对于操作系统来说, 一个任务就是一个进程(Process)

进程内的这些“子任务”称为线程(Thread)

真正的并行执行多任务只能在多核CPU上实现

多任务的实现有3种方式:

  多进程模式;
  多线程模式;
  多进程+多线程模式 
Python既支持多进程, 又支持多线程

1 多进程

  Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。普通的函数调用,调用一次,返回一次,但是fork()调用一次,返回两次, 因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程),然后,分别在父进程和子进程内返回。

  子进程永远返回0, 而父进程返回子进程的ID, 进程只需要调用getppid()就可以拿到父进程的ID

  在python中可以通过导入os模块来完成一些系统的调用

  os.getpid()可以返回当前进程的pid

  os.fork()可以调用fork系统调用, 只不过只是支持linux系列的系统

1.1  multiprocessing

  由于在windows上无法使用fork(), 所以在python中提供了模块multiprocessing来形成子进程

  导入multiprocessing模块的方法是使用from multiprocessing import带入

  利用process函数来创建一个子进程

  第一个参数可以是用target用于传递一个函数, 用于生成进程之后调用该方法

  第二个参数是args传递的剩余参数

  使用start()方法来启动子进程

  join()方法表示父进程要等待子进程执行完毕之后才能继续往下执行, 通常用于进程间的同步

  具体的使用实例如下

from multiprocessing import Process
import os

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

if __name__=='__main__':
    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.')

1.2 Pool

  要创建大量的进程就需要使用进程池

  同样是multiprocessing模块下的, 但是使用的函数是Pool

  具体是Pool()可以传入一个值用于设定子进程同时执行的数量, 返回一个进程池

  Pool默认的大小是CPU的内核数量

  进程池可以调用apply_async()函数来创建子进程, 同样第一个参数可以绑定一个方法, 第二个参数args

  对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process

  具体创建代码

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)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')

1.3 子进程

  如果不仅要创建执行子进程, 还需要控制进程的输入和输出, 那就需要使用subprocess模块

  具体代码如下

import subprocess

print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org'])
print('Exit code:', r)

1.4 进程间的通信

  进程之间还需要通信, python通过Queue和Pipes来交换数据

  下面是创建两个进程, 一个是往Queue里写入数据, 一个是从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()

2 多线程

  一个进程至少有一个线程

  线程是操作系统直接支持的执行单元    

  在python中提供两个模块进程线程的操作, 一个是_thread, 一个是threading

  其中_thread是低级模块, threading是高级模块, 对_thread进程了封装, 一般只使用threading就行

  启动一个线程就是把一个函数传入并创建Thread实例, 然后调用start()开始执行

  由于任何进程默认就会启动一个线程,我们把该线程称为主线程, 主线程又可以启动新的线程

  Python的threading模块有个current_thread()函数,它永远返回当前线程的实例

  主线程实例的名字叫MainThread,子线程的名字在创建时指定,我们用LoopThread命名子线程

  名字仅仅在打印时用来显示,完全没有其他意义,如果不起名字Python就自动给线程命名为Thread-1,Thread-2……

  具体代码如下

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)

2.1 Lock

  多线程和多进程的区别

  多进程中, 同一个变量, 各自有一份拷贝, 互相不影响

  多线程中, 所有变量都是有所有线程共享, 任何一个变量都可以被任何一个线程修改, 所以一定要注意同时修改一个变量的情况

  因此可以使用锁来实现对并发修改的控制

balance = 0
lock = threading.Lock()

def run_thread(n):
    for i in range(100000):
        # 先要获取锁:
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release()

  

    

   

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值