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中使用第三方库xlrd来写入Excel文件示例

继上一篇文章使用xlrd来读Excel之后,这一篇文章就来介绍下,如何来写Excel,写Excel我们需要使用第三方库xlwt,和xlrd一样,xlrd表示read xls,xlwt表示...

tensorflow学习笔记之简单的神经网络训练和测试

tensorflow学习笔记之简单的神经网络训练和测试

本文实例为大家分享了用简单的神经网络来训练和测试的具体代码,供大家参考,具体内容如下 刚开始学习tf时,我们从简单的地方开始。卷积神经网络(CNN)是由简单的神经网络(NN)发展而来的,...

python os.path.isfile 的使用误区详解

下列这几条语句,看出什么问题了不? for file in os.listdir(path): if os.path.isfile(file) and os.path.spl...

Python守护进程(daemon)代码实例

# -*-coding:utf-8-*- import sys, os '''将当前进程fork为一个守护进程 注意:如果你的守护进程是由inetd启动的,不要这样做!ine...

Python 模拟购物车的实例讲解

Python 模拟购物车的实例讲解

1.功能简介 此程序模拟用户登陆商城后购买商品操作。可实现用户登陆、商品购买、历史消费记查询、余额和消费信息更新等功能。首次登陆输入初始账户资金,后续登陆则从文件获取上次消费后的余额,每...