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笔记(2)

继续List: 删除元素: 复制代码 代码如下: a =[1, 2, 3, 4] a[2:3] = [] #[1, 2, 4] del a[2] #[1, 2] 清空list 复制代码...

python关闭windows进程的方法

本文实例讲述了python关闭windows进程的方法。分享给大家供大家参考。具体如下: 下面的python代码根据进程的名字调用windows的taskkill命令关闭指定的进程...

python各类经纬度转换的实例代码

python各类经纬度转换的实例代码

python各类经纬度转换,具体代码如下所示: import math import urllib import json x_pi = 3.14159265358979324 *...

基于python 处理中文路径的终极解决方法

1 、据说python3就没有这个问题了 2 、u'字符串' 代表是unicode格式的数据,路径最好写成这个格式,别直接跟字符串'字符串'这类数据相加,相加之后type就是str,这样...

Python中装饰器兼容加括号和不加括号的写法详解

使用Django的时候,我发现一个很神奇的装饰器: @login_required, 这是控制一个view的权限的,比如一个视图必须登录才可以访问,可以这样用: @login_req...