Python2.7实现多进程下开发多线程示例

yipeiwu_com6年前Python基础

简单的基于Python2.7版本的多进程下开发多线程的示例,供大家参考,具体内容如下

可以使得程序执行效率至少提升10倍

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Time : 2018/10/24
 @Author : LiuXueWen
 @Site : 
 @File : transfer.py
 @Software: PyCharm
 @Description: 
"""

import os
import traceback
import threading
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool


# 兼容python2.7上多线程的bug,不加上下面的反代理程序不能正常执行
def proxy(cls_instance, i):
 return cls_instance.multiprocess_thread(i)
def proxy2(cls_instance, i):
 return cls_instance.file_operation(i)

class file2transfer():
 # 多进程执行程序
 def multiprocessingTransferFiles(self):
  try:
   # 创建进程池
   p = Pool()
   //参数末尾必须加上逗号
   p.apply_async(proxy, args=(self, self.root_path,))
   p.close()
   p.join()
  except Exception as e:
   print(e)

 # 每个进程下的多线程执行,线程数等于当前机器的核数
 def multiprocess_thread(self, root_path):
  try:
   # 创建线程锁
   lock = threading.RLock()
   lock.acquire()
   # 获取每个文件
   for pfile in os.listdir(root_path):
    # 获取文件的完整路径
    full_file_path = os.path.join(root_path, pfile)
    # 多线程读写文件
    p = ThreadPool()
    # 执行线程
    p.apply_async(proxy2, args=(self, full_file_path,))
    p.close()
    p.join()
  except Exception as e:
   print(e)
  finally:
   # 释放线程锁
   lock.release()

 # 对每个文件夹下的每个文件进行操作
 def file_operation(self, full_file_path):
  try:
   // TODO 真正需要单独执行的操作
   pass
  except Exception as e:
   print(e)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

PyQtGraph在pyqt中的应用及安装过程

PyQtGraph在pyqt中的应用及安装过程

1.PyQtGraph简介: pyqtgraph的主要用途: 1、为数据、绘图、视频等提供快速、可交互图形显示。 2、提供快速开发应用的工具。 2.PyQtGraph的安装: pip i...

django获取from表单multiple-select的value和id的方法

如下所示: <select id="host_list" name="host_list" multiple> {% for op in host_list %}...

Python.append()与Python.expand()用法详解

如下所示: alist=[1,2]] >>>[1,2] alist.append([3,4]) >>>[1, 2, [3, 4]] alist...

基于Python和Scikit-Learn的机器学习探索

你好,%用户名%! 我叫Alex,我在机器学习和网络图分析(主要是理论)有所涉猎。我同时在为一家俄罗斯移动运营商开发大数据产品。这是我第一次在网上写文章,不喜勿喷。 现在,很多人想开...

TensorFlow用expand_dim()来增加维度的方法

TensorFlow中,想要维度增加一维,可以使用tf.expand_dims(input, dim, name=None)函数。当然,我们常用tf.reshape(input, sha...