python 在批量线程中运行可并行化的函数,等待每个批处理完成。这允许计算机的全部资源b

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 在批量线程中运行可并行化的函数,等待每个批处理完成。这允许计算机的全部资源b相关的知识,希望对你有一定的参考价值。

import threading
import os

# Normally this would be some busier function...  Here it is a stub.
def PlotAlphaMELTS(PathName):
    print PathName

# How many threads we want.
NumThreads = 10
# Counter for the thread in the loop.
ThreadCount = 0
# List of the threads.
threads = [None]*NumThreads

# You need a different parameter to each thread to make it do something different.
params = range(100)

# This part is really processor intensive, so let's multithread it.
for p in params:
    # Set up a thread.
    threads[ThreadCount] = threading.Thread(target=PlotAlphaMELTS, args=(p,))
    ThreadCount += 1
    
    # After making NumThreads threads, then we start them all.
    if ThreadCount % NumThreads == 0:
       for t in threads:
           # daemon mode so they run simultaneously.
           t.daemon = True
           t.start()
       # Now they are running.  Wait until they all finish.
       for t in threads:
           t.join()
       # And reset the counter so we do a new batch
       ThreadCount = 0

以上是关于python 在批量线程中运行可并行化的函数,等待每个批处理完成。这允许计算机的全部资源b的主要内容,如果未能解决你的问题,请参考以下文章

Parallel并行化编程

EffectivePython并发及并行

python 同步异步,并发并行,同步锁

Python并行编程:多线程性能评估

python-并发并行同步异步同步锁

使用不同的参数并行运行相同的函数,并知道哪个并行运行在 python 中结束了