\

Pythonで並列処理を行う際には、multiprocessingモジュールを使用します。このモジュールは、CPUのコアを複数扱うことで並列化を達成しています。

以下に、multiprocessingを使用した並列処理の基本的なコードを示します。

from multiprocessing import Pool

def calc(num_pair):
    x, y = num_pair
    low = min(x, y)
    gcd = 0  # Greatest common divisor
    for i in range(low, 0, -1):
        if x % i == 0 and y % i == 0:
            gcd = i
            break
    # Least common multiple
    lcm = x * y // gcd
    return gcd, lcm

if __name__ == "__main__":
    NUMBERS = [
        (12345678,24680246),(91845010,35889830),
        (82163657,75546871),(46015383,43872681),
        (73739990,64003993),(26514146,33211514),
        (51395783,78597259),(99939535,88084461)
    ]
    p = Pool(8)
    try:
        result = p.map(calc, NUMBERS)
    except Exception as e:
        print(e)
    print(f'result =  {result}')
    gcd = [i[0] for i in result]
    lcm = [j[1] for j in result]
    print(f'gcd =  {gcd}')
    print(f'lcm =  {lcm}')
    for i, pair in enumerate(NUMBERS):
        print(f'{pair[0]}と{pair[1]}の最大公約数は{gcd[i]}, 最小公倍数は{lcm[i]}です')

このコードでは、multiprocessing.Poolを使用して並列処理を行っています。Pool.mapメソッドを使用すると、関数の戻り値が増えるほど、resultの1つのタプルに入る数が増えます。

このように、Pythonのmultiprocessingモジュールを使用すると、簡単に並列処理を行うことができます。ただし、並列処理は複雑な問題を引き起こす可能性があるため、適切な知識と理解が必要です。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です