python多进程使用及线程池的使用方法代码详解

yipeiwu_com6年前Python基础

多进程:主要运行multiprocessing模块

import os,time
import sys
from multiprocessing import Process
class MyProcess(Process):
  """docstring for MyProcess"""
  def __init__(self, arg, callback):
    super(MyProcess, self).__init__()
    self.arg = arg
    self.callback = callback
  def run(self):
    self.callback(self.arg)
def test(arg):
  print("子进程{}开始>>> pid={}".format(arg,os.getpid()))
  for i in range(1,5):
    sys.stdout.write("子进程{}运行中{}\r".format(arg,i))
    sys.stdout.flush()
    time.sleep(1)
def main():
  print("主进程开始>>> pid={}".format(os.getpid()))
  myp=MyProcess(1,test)
  myp.start()
  myp2=MyProcess(2,test)
  myp2.start()
  myp.join()
  myp2.join()
  print("主进程终止")
if __name__ == '__main__':
  main()

线程池:主要运用了未来模块!下面例子,第一个是正常,第二第线程池,第三个用运行了2个线程池,会排队

from concurrent.futures import ThreadPoolExecutor
import time
def sayhello(a):
  print("hello: "+a)
  time.sleep(2)
def main():
  seed=["a","b","c"]
  start1=time.time()
  for each in seed:
    sayhello(each)
  end1=time.time()
  print("time1: "+str(end1-start1))
  start2=time.time()
  with ThreadPoolExecutor(3) as executor:
    for each in seed:
      executor.submit(sayhello,each)
  end2=time.time()
  print("time2: "+str(end2-start2))
  start3=time.time()
  with ThreadPoolExecutor(2) as executor1:
    executor1.map(sayhello,seed)
  end3=time.time()
  print("time3: "+str(end3-start3))
if __name__ == '__main__':
  main()

总结

以上所述是小编给大家介绍的python多进程使用及线程池的使用方法代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python中下标和切片的使用方法解析

下标 所谓下标就是编号,就好比超市中存储柜的编号,通过这个编号就能找到相应的存储空间。 Python中字符串,列表,元祖均支持下标索引。 例如: # 如果想取出部分字符,可使用下标...

Python基于Tkinter实现的记事本实例

本文实例讲述了Python基于Tkinter实现的记事本。分享给大家供大家参考。具体如下: from Tkinter import * root = Tk('Simple Edito...

Python函数中的可变长参数详解

Python函数中的可变长参数详解

一、Python函数中的参数 1、使用python的函数时,有参数类别,比如位置参数、关键字参数、可变长参数 2、位置参数、关键字参数很好理解,关键是可变长参数经常能见到,但是一直没有...

Python切片用法实例教程

本文以实例形式讲述了Python中切片操作的用法,分享给大家供大家参考借鉴,具体如下: 取一个list或tuple的部分元素是非常常见的操作。比如,一个list如下: >>...

使用Python实现 学生学籍管理系统

使用Python实现 学生学籍管理系统

大家好,今天跟大家分享一个用Python实现的学生学籍管理系统: 该代码主体由五个函数组成: 1.add_stu() 添加 2.del_stu() 删除 3.print_stu()打...