1

多分これは本当に簡単ですが、これを理解するのに少し問題があります。

私が抱えている課題は、親関数内から子並列関数を実行することです。その関数は、子の並列関数呼び出しの結果を待っている間に 1 回だけ実行する必要があります。

私のジレンマを示す小さな例を書きました。

import string
from joblib import Parallel, delayed
import multiprocessing

def jobToDoById(id):
    #do some other logic based on the ID given
    rand_str  = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(10))
    return [id, rand_str]


def childFunctionParallel(jobs):
    num_cores = multiprocessing.cpu_count()
    num_cores = num_cores - 1

    if __name__ == '__main__':
        p = Parallel(n_jobs=num_cores)(delayed(jobToDoById)(i) for i in jobs)
        return p

def childFunctionSerial(jobs):
    result = []
    for job in jobs:
        job_result = jobToDoById(job)
        result.append(job_result)
    return result



def motherFunction(countries_cities, doInParallel):
    result = []
    print("Start mainLogic")
    for country in countries_cities:
        city_list = countries_cities[country]
        if(doInParallel):
            cities_result = childFunctionParallel(city_list)
        else:
            cities_result = childFunctionSerial(city_list)
        result.append(cities_result)
        # ..... do some more logic

    # ..... do some more logic before returning
    print("End mainLogic")
    return result



print("Start Program")

countries_cities = {
    "United States" : ["Alabama", "Hawaii", "Mississippi", "Pennsylvania"],
    "United Kingdom" : ["Cambridge", "Coventry", "Gloucester", "Nottingham"],
    "France" : ["Marseille", "Paris", "Saint-Denis", "Nanterre", "Aubervilliers"],
    "Denmark" : ["Aarhus", "Slagelse", "Nykøbing F", "Rønne", "Odense"],
    "Australia" : ["Sydney", "Townsville", "Bendigo", "Bathurst", "Busselton"],
}
result_mother = motherFunction(countries_cities, doInParallel=True) # should be executed only once
print(result_mother) 
print("End Program")

doInParallelとの間を切り替えるTrueFalse、問題が表示されます。1回だけ実行して実行する場合childFunctionSerial()motherFunction()しかし、 を使用して実行すると、childFunctionParallelmotherFunction()複数回実行されます。どちらも同じ結果になりますが、私が抱えている問題は、motherFunction()一度だけ実行する必要があることです。

2 つの質問:

1.
マザー関数を 1 回実行し、その 内部から、同じマザー関数の複数のインスタンスを実行せずに並列ジョブを開始するように、プログラムを再構築する方法は?
2.jobToDoById()に加えて に2 番目のパラメータを渡すにはどうすればよいidですか?

4

1 に答える 1