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

yipeiwu_com5年前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使用LDAP做用户认证的方法

LDAP(Light Directory Access Portocol)是轻量目录访问协议,基于X.500标准,支持TCP/IP。 LDAP目录以树状的层次结构来存储数据。每个目录记...

解决python中 f.write写入中文出错的问题

一个出错的例子 #coding:utf-8 s = u'中文' f = open("test.txt","w") f.write(s) f.close() 原因是编码方式错误,应该...

python导包的几种方法(自定义包的生成以及导入详解)

python导包的几种方法(自定义包的生成以及导入详解)

python是一门灵活的语言,也可以说python是一门胶水语言,顾名思义,就是其可以导入各类的包,python的包可以说是所有语言中最多的。当然导入包大部分是为了更快捷,更方便,效率更...

django的model操作汇整详解

django的model操作汇整详解

单表操作 增加数据 auther_obj = {"auther_name":"崔皓然","auther_age":1} models.auther.objects.create(...

处理Selenium3+python3定位鼠标悬停才显示的元素

先给大家介绍下Selenium3+python3--如何定位鼠标悬停才显示的元素 定位鼠标悬停才显示的元素,要引入新模块 # coding:utf-8 from selenium...