我们的电脑总是可以打开很多的程序,而且相同的程序会同时实现多个功能。这就是多进程和多线程!

多进程

multiprocessing

Unix/Linux操作系统提供了一个fork()系统调用,可是Windows上面无法调用。
由于Python是跨平台的,自然也应该提供一个跨平台的多进程支持。multiprocessing模块就是跨平台版本的多进程模块。

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.')
运行结果:
Parent process 12588.
Child process will start.
Run child process test (11108)...
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.')
运行结果:
Parent process 16320.
Waiting for all subprocesses done...
Run task 0 (3480)...
Run task 1 (7388)...
Run task 2 (14396)...
Run task 3 (14288)...
Task 2 runs 0.43 seconds.
Run task 4 (14396)...
Task 0 runs 0.44 seconds.
Task 4 runs 0.49 seconds.
Task 1 runs 1.58 seconds.
Task 3 runs 2.92 seconds.
All subprocesses done.

多线程

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

# 新线程执行的代码:
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)
运行结果:
thread MainThread is running...
thread LoopThread is running...
thread LoopThread >>> 1
thread LoopThread >>> 2
thread LoopThread >>> 3
thread LoopThread >>> 4
thread LoopThread >>> 5
thread LoopThread ended.
thread MainThread ended.

周兆东
107 声望21 粉丝

一个java小白的成长之路。。。