python多线程与多进程

python多线程与多进程

多线程

  • threading模块

python自带模块,不能实现进程池控制

用法

python
my_thread_1 = threading.Thread(target=task1, name='T1') #创建一个进程
my_thread_2 = threading.Thread(target=task2, name='T2')
my_thread_1.start() #启动进程
my_thread_2.start()
my_thread_1.join()
print('all done')

  • threadpool模块

因为我们有时候有多个任务需要持续开启线程,但是又不能无限制开启(线程数量并不是越多越好,超过某个阈值反而效率会下降),需要控制线程数量,threadpool可以实现进程池的控制,

# 用threadpool模块
def t2():
    paramter = [(None, None) for i in range(5)]
    pool = threadpool.ThreadPool(8)
    # 构造任务
    requests = threadpool.makeRequests(test, paramter)
    # 启动任务
    [pool.putRequest(req) for req in requests]
    # 上面这句等同于 map(pool.putRequest, requests) 和 for req in requests pool.putRequest(req)
    pool.wait()

注意

  • makeRequests函数的第二个参数是调用函数的参数,类型必须是迭代器
  • 迭代器里面的每一个元素的类型为二元元组,且元组的第二个参数一般为None

  • ThreadPoolExecutor模块

未来使用的多线程模块,(听说threadpool已经太老),系统自带

from concurrent.futures import ThreadPoolExecutor

from concurrent.futures import  ThreadPoolExecutor


executor = ThreadPoolExecutor(8)
def test(a, b):
    time.sleep(1)
    print(a+b)

# 用系统自带的THreadpoolExecutor
def t1():
    executor.map(test, range(10), range(10,20))

注意

map函数第一个参数是要运行的函数,后面依次是此函数的参数

多进程

from multiprocessing import  Pool

多进程

阅读: 222002


要让Python程序实现多进程(multiprocessing),我们先了解操作系统的相关知识。

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

子进程永远返回0,而父进程返回子进程的ID。这样做的理由是,一个父进程可以fork出很多子进程,所以,父进程要记下每个子进程的ID,而子进程只需要调用getppid()就可以拿到父进程的ID。

Python的os模块封装了常见的系统调用,其中就包括fork,可以在Python程序中轻松创建子进程:

import os

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 (876) start...
I (876) just created a child process (877).
I am child process (877) and my parent is 876.

由于Windows没有fork调用,上面的代码在Windows上无法运行。由于Mac系统是基于BSD(Unix的一种)内核,所以,在Mac下运行是没有问题的,推荐大家用Mac学Python!

有了fork调用,一个进程在接到新任务时就可以复制出一个子进程来处理新任务,常见的Apache服务器就是由父进程监听端口,每当有新的http请求时,就fork出子进程来处理新的http请求。

multiprocessing

multiprocessing模块就是跨平台版本的多进程模块。

multiprocessing模块提供了一个Process类来代表一个进程对象,下面的例子演示了启动一个子进程并等待其结束:

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.')

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)
    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.')

你可能感兴趣的:(python)