<p>Python全局解释器锁或GIL只允许一个线程控制Python解释器。由于函数<code>calculateScore</code>可能受cpu限制,并且需要解释器执行其字节码,因此使用线程可能没有什么好处。另一方面,如果它主要执行I/O操作,那么它将在大部分运行时间内放弃GIL,允许其他线程运行。但这里的情况似乎并非如此。您可能应该使用来自<code>concurrent.futures</code>的<code>ProcessPoolExecutor</code>(两种方法都尝试一下,然后查看):</p>
<pre><code>def main():
with ProcessPoolExecutor(max_workers=None) as executor:
the_futures = {}
for i in range(len(fullAnalysis)):
text = fullAnalysis['QueryText'][i]
arg = 'most_similar'+ ' ' + text
future = executor.submit(calculateScore, arg)
the_futures[future] = i # map future to request
for future in as_completed(the_futures): # results as they become available not necessarily the order of submission
i = the_futures[future] # the original index
result = future.result() # the result
</code></pre>
<p>如果从<code>ProcessPoolExecutor</code>构造函数中省略<code>max_workers</code>参数(或指定值<code>None</code>),默认值将是您机器上的处理器数量(不是一个坏的默认值)。指定大于现有处理器数量的值没有意义</p>
<p>如果您不需要将未来与原始请求联系起来,那么<code>the_futures</code>可以只是一个列表,但最简单的是,您甚至不用麻烦使用<code>as_completed</code>方法:</p>
<pre><code>def main():
with ProcessPoolExecutor(max_workers=5) as executor:
the_futures = []
for i in range(len(fullAnalysis)):
text = fullAnalysis['QueryText'][i]
arg = 'most_similar'+ ' ' + text
future = executor.submit(calculateScore, arg)
the_futures.append(future)
# wait for the completion of all the results and return them all:
results = [f.result() for f in the_futures()] # results in creation order
return results
</code></pre>
<p>应该提到的是,启动<code>ProcessPoolExecutor</code>函数的代码应该位于由<code>if __name__ = '__main__':</code>控制的块中。如果不是,您将进入一个递归循环,每个子进程都会启动<code>ProcessPoolExecutor</code>。但这里似乎就是这样。也许你想一直使用<code>ProcessPoolExecutor</code></p>
<p>此外:</p>
<p>我不知道这句话是什么意思</p>
<pre><code>model = gensim.models.Word2Vec.load('w2v_model_bigdata')
</code></pre>
<p>。。。在函数<code>calculateStore</code>中。它可能是一个i/o绑定语句。但这似乎并没有因电话而异。如果是这种情况,并且函数中没有修改<code>model</code>,那么该语句不应该移出函数并只计算一次吗?那么这个函数显然会运行得更快(而且显然受到cpu的限制)</p>
<p>此外:</p>
<p>异常块</p>
<pre><code>except KeyError as ke:
#print(str(ke) + "\n")
inp = input()
</code></pre>
<p>。。。这令人费解。您输入的值在返回之前永远不会被使用。如果要暂停执行,则不会输出错误消息</p>