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中的 is 和 == 以及字符串驻留机制详解

is 和 == 先了解下官方文档中关于 is 和 == 的概念。is 表示的是对象标示符(object identity),而 == 表示的是相等(equality);is 的作用是用...

使用tensorflow实现线性回归

使用tensorflow实现线性回归

本文实例为大家分享了tensorflow实现线性回归的具体代码,供大家参考,具体内容如下 一、随机生成1000个点,分布在y=0.1x+0.3直线周围,并画出来 import ten...

python实现傅里叶级数展开的实现

python实现傅里叶级数展开的实现

傅立叶级数的介绍我就不说了,自己也是应用为主,之前一直觉得很难懂,但最近通过自己编程实现了一些函数的傅立叶级数展开之后对傅立叶 级数展开的概念比较清楚了 (1)函数如下 函数图象如...

Python工程师面试题 与Python基础语法相关

希望通过本文能够帮助大家顺顺利利通过Python面试,之后还有一篇关于Python Web相关的文章欢迎大家阅读。 1、Python中pass语句的作用是什么? pass语句什么也不做,...

解决Python print 输出文本显示 gbk 编码错误问题

前阵子想爬点东西,结果一直提示错误UnicodeEncodeError: ‘gbk' codec can't encode character ‘\xa0' in position,在网...