|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- encoding: utf-8 -*- |
| 3 | +""" |
| 4 | +Topic: 多线程示例程序 |
| 5 | +Desc : |
| 6 | +""" |
| 7 | + |
| 8 | +from multiprocessing import Process |
| 9 | +import os |
| 10 | + |
| 11 | +# 子进程要执行的代码 |
| 12 | +def run_proc(name): |
| 13 | + print('Run child process %s (%s)...' % (name, os.getpid())) |
| 14 | + |
| 15 | +if __name__=='__main__': |
| 16 | + print('Parent process %s.' % os.getpid()) |
| 17 | + p = Process(target=run_proc, args=('test',)) |
| 18 | + print('Child process will start.') |
| 19 | + p.start() |
| 20 | + p.join() |
| 21 | + print('Child process end.') |
| 22 | + |
| 23 | + |
| 24 | +from multiprocessing import Pool |
| 25 | +import os, time, random |
| 26 | + |
| 27 | +def long_time_task(name): |
| 28 | + print('Run task %s (%s)...' % (name, os.getpid())) |
| 29 | + start = time.time() |
| 30 | + time.sleep(random.random() * 3) |
| 31 | + end = time.time() |
| 32 | + print('Task %s runs %0.2f seconds.' % (name, (end - start))) |
| 33 | + |
| 34 | +if __name__=='__main__': |
| 35 | + print('Parent process %s.' % os.getpid()) |
| 36 | + p = Pool(4) |
| 37 | + for i in range(5): |
| 38 | + p.apply_async(long_time_task, args=(i,)) |
| 39 | + print('Waiting for all subprocesses done...') |
| 40 | + p.close() |
| 41 | + p.join() |
| 42 | + print('All subprocesses done.') |
| 43 | + |
| 44 | + |
| 45 | +from multiprocessing import Process, Queue |
| 46 | +import os, time, random |
| 47 | + |
| 48 | +# 写数据进程执行的代码: |
| 49 | +def write(q): |
| 50 | + print('Process to write: %s' % os.getpid()) |
| 51 | + for value in ['A', 'B', 'C']: |
| 52 | + print('Put %s to queue...' % value) |
| 53 | + q.put(value) |
| 54 | + time.sleep(random.random()) |
| 55 | + |
| 56 | +# 读数据进程执行的代码: |
| 57 | +def read(q): |
| 58 | + print('Process to read: %s' % os.getpid()) |
| 59 | + while True: |
| 60 | + value = q.get(True) |
| 61 | + print('Get %s from queue.' % value) |
| 62 | + |
| 63 | +if __name__=='__main__': |
| 64 | + # 父进程创建Queue,并传给各个子进程: |
| 65 | + q = Queue() |
| 66 | + pw = Process(target=write, args=(q,)) |
| 67 | + pr = Process(target=read, args=(q,)) |
| 68 | + # 启动子进程pw,写入: |
| 69 | + pw.start() |
| 70 | + # 启动子进程pr,读取: |
| 71 | + pr.start() |
| 72 | + # 等待pw结束: |
| 73 | + pw.join() |
| 74 | + # pr进程里是死循环,无法等待其结束,只能强行终止: |
| 75 | + pr.terminate() |
| 76 | + |
0 commit comments