본문 바로가기

프로그래밍언어/Python

[Python] Python 병렬처리 - threading (2)

반응형

[threading - Thread-based parallelism]

Thread Objects

 

Thread class 개별 제어 thread에서 실행하는 활동을 나타낸다. thread가 실행할 활동은 run() 메소드를 override 하거나 callable object를 전달하여 설정할 수 있다. ( override 시에는 __init__과 run() 메소드만 override 해야한다.) 각 thread의 활동을 시작하도록 하기 위해서는 start() 메소드를 호출한다. start 메소드는 thread의 run() 메소드를 실행시킨다. thread 활동을 시작하면 alive 상태가 되는데, run() 메소드가 종료되거나 예외 발생 시에 alive 상태가 해제된다. alive 상태는 is_alive() 메소드를 사용하여서 확인할  있다.

 

 thread 다른 thread join() 메소드를 호출하여 실행 흐름을 제어할  있다. join() 메소드는 join() 메소드가 호출된thread 종료될 때까지 호출한 thread 실행을 막는다.

 

각 thread 객체 이름을 가지고 있는데, 객체의 name attribute 통해서 읽거나 변경할  있다

 

만약 run() 메소드가 예외를 발생시키는 경우 threading.execepthook() 호출되어서 예외를 처리한다.

 

thread daemon thread 플래그 되는데, 이를 통해서 daemon thread 남았을  전체 파이썬 프로그램을 종료시킨다. deamon thraed는 기본적으로 해당 thread를 생성한 parent thread로부터 상속받는다. 이외에 daemon 값을 변경하기 위해서는 thread 생성자의 daemon 파라미터나 thread의 daemon 속성을 통해서 설정할 수 있다.

 

  - main thread 객체

    • 파이썬 프로그램의 초기 제어 thread

  - dummy thread 객체

    • 외부 thread 해당하는 객체들로 C코드에서 직접 만든 threading 모듈 외부에서 생성된 객체들로 제한적인 기능을 제공한다.

 

■ threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

  - Thread 생성자이다.

  - group: ThreadGroup 구현될  향후 확장을 위해서 예약되어 있다.

  - target: run() 메소드에 의해서 호출될 callable object

  - name: thread name

  - args: target 호출을 위한 argument tuple

  - kwargs: target 호출을 위한 keyword arguments dictionary

  - daemon: thread daemon인지를 명시적으로 설정

 

  - start()

    •thread 활동 시작 함수

 

  - run()

    • thread 활동을 나타내는 메소드. subclass에서 override 해서 사용

 

  - join(timeout=None)

    • thread 소멸될 때까지 대기한다. join() 메소드가 호출된 thread 소멸되거나timeout 시간이 지날 때까지 호출한. thread 대기한다.

 

  - name

    • thread 식별 목적으로 설정해주는 이름으로 여러 thread 들에게 같은 이름을   있다.

 

  - getName(), setName()

    • old getter/setter API for name

 

  - ident

    • 현재 thread 식별자. 아직 활동을 시작하지 않은 thread 경우 None 가진다.

 

  - native_id

    • 해 thread native integral thread ID. OS 커널에 의해서 할단된 Thread ID (TID) 이다.

 

  - is_alive()

    • thread 현재 alive 상태인지 아닌지 반환한다.

 

  - daemon

    • 현재 thread daemon thread 인지 아닌지를 반환한다. start() 호출되기 전에 설정되어야한다. 그렇지 않으면 RuntimeError 발생한다.

 

  - isDaemon(), setDaemon()

    • old gettter/setter API for daemon

 

<reference>

- Python Documentation >> The Python Standard Library >> Concurrent Execution

반응형