标签:pool child 对象 快速 star call time() 运行 操作系统
多进程模式;  多线程模式;  多进程+多线程模式。小结:
线程是最小的执行单元,而进程由至少一个线程组成。如何调度进程和线程,完全由操作系统决定,程序自己不能决定什么时候执行,执行多长时间。  多进程和多线程的程序涉及到同步、数据共享的问题,编写起来更复杂。
- - -
PYTHON   # windows 没有 fork()方法,此方法适用于/unix/linux/mac   import os   print(‘Process(%s)start...‘% os.getpid())   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))# windows 多进程
from multiprocessing import Process
import os
# 子进程执行
def run_proc(name):
    print(name+'进程{s}'.format(s=os.getpid()))
if __name__ == '__main__':
    # 获取当前主线册程id
    print('当前线程id%s'% os.getpid())
    # 创建子线程
    p = Process(target=run_proc,args=('子进程',))
    print('调用Start')
    # 启动线程
    p.start()
    # join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。
    p.join()
    print('end') 代码:
```PYTHON
# Pool:如果要启动大量的子进程,可以用进程池的方式批量创建子进程:
from multiprocessing import Pool
import os,time,random
def long_time(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)))
代码:
```PYTHON
# 子进程:subprocess模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出。
import subprocess
代码:
```PYTHON
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()
```
标签:pool child 对象 快速 star call time() 运行 操作系统
原文地址:https://www.cnblogs.com/thloveyl/p/11483266.html