【问题标题】:Convert multithreading to multiprocessing in Python在 Python 中将多线程转换为多处理
【发布时间】:2015-10-18 06:22:40
【问题描述】:

如何将这个东西从多线程转换为多处理?使用多线程,它实际上运行速度较慢,而使用的 CPU 并不多。所以我希望多处理可能会有所帮助。

  def multiprocess(sentences):

     responselist = []

     #called by each thread
     def processfunction(asentence,i):
         pro_sentence = processthesentence(asentence[0],asentence[1],asentence[2],asentence[3],asentence[4],asentence[5],asentence[6],asentence[7],asentence[8])
         mytyple = asentence,pro_sentence
         responselist.append(mytyple)

     # ----- function end --------- #

     #start threading1
     threadlist = []
     for i in range (2):
         asentence = sentences[i]
         t = Thread(target=processfunction, args=(asentence,i,))
         threadlist.append(t)
         t.start()

     for thr in threadlist:
         thr.join()

     return responselist

我试过这个(用进程替换一个词 - 线程,但这不起作用):

  from multiprocessing import Process 

  def processthesentence(asentence):
      return asentence + " done"

  def multiprocess(sentences):

     responselist = []

     #called by each thread
     def processfunction(asentence,i):
         pro_sentence = processthesentence(asentence)
         mytyple = asentence,pro_sentence
         responselist.append(mytyple)

     # ----- function end --------- #

     #start threading1
     threadlist = []
     for i in range (2):
         asentence = sentences[i]
         t = Process(target=processfunction, args=(asentence,i,))
         threadlist.append(t)
         t.start()

     for thr in threadlist:
         thr.join()

     return responselist


  sentences = []
  sentences.append("I like apples.")
  sentences.append("Green apples are bad.")
  multiprocess(sentences) 

尝试使用 greenevent 但出现一些错误:

import greenlet
import gevent

def dotheprocess(sentences):

    responselist = []

    #called by each thread
    def task(asentence):
        thesentence = processsentence(asentence[0],asentence[1],asentence[2],asentence[3],asentence[4],asentence[5],asentence[6],asentence[7],asentence[8])

        mytyple = asentence,thesentence
        responselist.append(mytyple)

    # ----- function end --------- #

    def asynchronous():
        threads = [gevent.spawn(task, asentence) for asentence in sentences]
        gevent.joinall(threads)   

    asynchronous()

    return responselist

【问题讨论】:

  • 我试图用进程替换一个词 - 线程,但这不起作用,因为我猜你不能在数组中添加进程。我在问题中添加了代码。
  • 看起来您刚刚添加了一个额外的import。为什么它会改变什么?
  • @alfasin - 错误我也用进程替换了线程。但这会导致错误。
  • 1.我不明白你是如何运行它的。 2.“但这不起作用”太模糊了——究竟什么不起作用,预期输出是什么,实际输出是什么。你有错误吗?如果是这样,发布堆栈跟踪...
  • 你在函数processfunction()中使用了变量i的什么地方

标签: python multiprocessing python-2.6 python-multiprocessing


【解决方案1】:

尝试使用gevent 生成多个greenlet,让您可以使用其他CPU。这是根据您的示例。看到一个 Queue 是用来在 gevent 的上下文切换中正常工作的

导入greenlet
导入 gevent
从 gevent 导入猴子
猴子.patch_all()

def dotheprocess(句子):
    队列 = gevent.queue.Queue()
    #每个线程调用

    def 任务(句子):
        thesentence = processessentence(asentence[0],asentence[1],asentence[2],asentence[3],asentence[4],asentence[5],asentence[6],asentence[7],asentence[8])
        queue.put((句子,句子))

    threads = [gevent.spawn(task, asentence) 用于句子中的句子]
    gevent.joinall(线程)

    返回队列
#用你的句子调用dotheprocess函数

【讨论】:

  • 我写了代码但是我得到了一个错误 - import greenlet ImportError: DLL load failed: The specified procedure could not be found.
  • 对不起。仅适用于 Linux。 Dll 仅适用于 Windows
  • 你应该更好地指定你的目标操作系统是什么
  • 我在linux上也可以安装,有帮助,请看上面的代码,看看是否可以。
  • 你为什么不赞成这个答案?对于您的问题,这是一个有效的问题。这些行动不会帮助您获得帮助
【解决方案2】:

除非您的线程中有一些等待函数(I/O 实现),否则线程不会使函数更快。多处理在理论上会有所帮助,但是由于开销,简单的函数不会从中受益太多,因此请谨慎使用。使用Manager 作为共享变量。

from multiprocessing import Process, Manager, freeze_support

class multiProcess():
    def __init__(self, sentences):
        self.responseList = Manager().list()
        self.processList = []
        self.sentences = sentences

    def processSentence(self,a0,a1,a2,a3,a4,a5,a6,a7,a8):
        reversedValue = a8+a7+a6+a5+a4+a3+a2+a1+a0
        return reversedValue

    #called by each process
    def processFunction(self,asentence):
        pro_sentence = self.processSentence(asentence[0],asentence[1],asentence[2],asentence[3],asentence[4],asentence[5],asentence[6],asentence[7],asentence[8])
        mytuple = (asentence,pro_sentence)
        self.responseList.append(mytuple)
        return

    def run(self):
        for i in range(2):
            asentence = self.sentences[i]
            p = Process(target=self.processFunction, args=(asentence,))
            self.processList.append(p)
            p.start()

        for pro in self.processList:
            pro.join()

        return self.responseList


if __name__=="__main__":
    freeze_support()
    sentences = ['interesting','wonderful']
    output = multiProcess(sentences).run()
    print(output)

【讨论】:

  • 非常感谢。我运行它,但我遇到了很多错误。可能是因为我用的是 python 2.7.3?
  • 我只用python2.7.9 对其进行了测试,但基本上使用Manager 你应该没问题
  • if name__=="__main": 是什么意思?我必须使用它吗?我可以在函数中使用它吗?我知道这是基本的,但在我编写了很多脚本之后,到目前为止我从未使用过它。
  • 你应该自己google一下,不在这里你不必使用它,它是用于转储测试
  • 酷。所以你在这里没有得到任何错误?你可能在linux上运行吗?我在窗户上?
【解决方案3】:

这对我来说效果最好——它比不使用它快 50% 左右:

def processthesentence(asentence):
     return asentence

import multiprocessing as mympro 
if __name__=="__main__":
    sentences = ['I like something','Great cool']
    numberofprocesses = 3
    thepool = mympro.Pool(processes=numberofprocesses)
    results = [thepool.apply_async(processthesentence, args=(asent,)) for asent in sentences]
    output = [item.get() for item in results]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 2018-03-06
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多