본문 바로가기
카테고리 없음

bash 멀티프로세싱

by IT트레이서 2023. 8. 4.

상황

bash shell 환경에서 함수 단위로 병렬 실행 해야하는 상황

예제 샘플

#!/bin/bash

function function1() {
  echo "Function 1 started..."
  sleep 5  # Simulate some task in function 1
  echo "Function 1 completed."
}

function function2() {
  echo "Function 2 started..."
  sleep 3  # Simulate some task in function 2
  echo "Function 2 completed."
}

# Run function1 in the background and get its PID
function1 &
function1_pid=$!

function2 &

# Wait for all background jobs to finish
wait

echo "All functions completed. https://lifesoon.tistory.com/manage/newpost/22 "

echo "PID of Function 1: $function1_pid"

& 심볼을 사용하여 백그라운드에서 함수가 실행 할 수 있게 할 수 있다.

$!  을 사용하여 바로 이전에 백그라운로 실행한 함수의 프로세스 아이디를 가져올 수 있다.

wait 명령어는 백그라운드로 실행한 함수들이 종료될때까지 기다린다.

wait 명령어로 특정 프로세스가 종료되기를 기다리게 할려면 wait 다음에 인자로서 프로세스 아이드를 주면 된다.

이와 비슷한 코드를 파이썬으로도 구현해 볼 수 있다.

import multiprocessing
import time

def function1(arg):
    print("Function 1 started with argument:", arg)
    time.sleep(5)  # Simulate some task in function 1
    print("Function 1 completed.")

def function2():
    print("Function 2 started...")
    time.sleep(3)  # Simulate some task in function 2
    print("Function 2 completed.")

if __name__ == "__main__":
    # Create two separate processes for function1 and function2
    arg_for_function1 = "Hello, this is an argument!"
    process1 = multiprocessing.Process(target=function1, args=(arg_for_function1,))
    process2 = multiprocessing.Process(target=function2)

    # Start both processes (they will run in parallel)
    process1.start()
    process2.start()

    # Wait for both processes to finish
    process1.join()
    process2.join()

    print("All functions completed. https://lifesoon.tistory.com/22")

multiprocessing.Process 클래스의 생성자 인자로 함수 이름을 넘겨준다. 

이때 args로 전달될 함수의 매개변수도 튜플 형태로 같이 전달해 줄 수 있다.

프로세스객체에 start 멤버 함수로 프로세스를 시작하고

join 메서드가 각 프로세스의 종료를 기다린다.