【发布时间】: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