Python

【基础】练习册53-Python3_进程1

2021-02-19  本文已影响0人  Alyna_C

进程1

代码如下:

# -*- coding: utf-8 -*-

# process_apply.py

# @author Alyna

# @description

# @created 2020-05-12T14:28:48.220Z+08:00

# @last-modified 2020-05-12T15:22:41.372Z+08:00

#

import multiprocessing

import os

import time

def run_task(name):

  print('Task {0} pid {1} is running, parent id is {2}'.format(name, os.getpid(), os.getppid()))

  time.sleep(1)

  print('Task {0} end.'.format(name))

if __name__ == '__main__':

  print('current process {0}'.format(os.getpid()))

  #设定池内进程数

  p = multiprocessing.Pool(processes=3)

  for i in range(6):

    p.apply(run_task, args=(i,)) #只允许单个进入池子

    #p.apply_async(run_task, args=(i,)) #同步执行进程

  print('Waiting for all subprocesses done...')

  p.close()

  p.join()

  print('All processes done!')

运行结果为:

上一篇下一篇

猜你喜欢

热点阅读