>  기사  >  백엔드 개발  >  Python의 스레딩 모듈을 통해 스레드 정의 및 호출

Python의 스레딩 모듈을 통해 스레드 정의 및 호출

高洛峰
高洛峰원래의
2017-02-28 17:22:311310검색

스레드 정의

가장 간단한 방법: target을 사용하여 스레드가 실행할 대상 함수를 지정한 다음 start()를 사용하여 시작합니다.

구문:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

그룹은 항상 None이며 향후 사용을 위해 예약되어 있습니다. target은 실행할 함수의 이름입니다. name은 스레드 이름이고 기본값은 Thread-N이며 일반적으로 기본값을 사용할 수 있습니다. 그러나 서버 측 프로그램 스레드 기능이 다른 경우에는 이름을 지정하는 것이 좋습니다.

#!/usr/bin/env python3
# coding=utf-8
import threading

def function(i):
  print ("function called by thread {0}".format(i))
threads = []

for i in range(5):
  t = threading.Thread(target=function , args=(i,))
  threads.append(t)
  t.start()
  t.join()

실행 결과:

$ ./threading_define.py

function called by thread 0
function called by thread 1
function called by thread 2
function called by thread 3
function called by thread 4

현재 스레드 확인

#!/usr/bin/env python3
# coding=utf-8

import threading
import time

def first_function():
  print (threading.currentThread().getName()+ str(' is Starting \n'))
  time.sleep(3)
  print (threading.currentThread().getName()+ str( ' is Exiting \n'))
  
def second_function():
  print (threading.currentThread().getName()+ str(' is Starting \n'))
  time.sleep(2)
  print (threading.currentThread().getName()+ str( ' is Exiting \n'))
  
def third_function():
  print (threading.currentThread().getName()+\
  str(' is Starting \n'))
  time.sleep(1)
  print (threading.currentThread().getName()+ str( ' is Exiting \n'))
  
if __name__ == "__main__":
  t1 = threading.Thread(name='first_function', target=first_function)
  t2 = threading.Thread(name='second_function', target=second_function)
  t3 = threading.Thread(name='third_function',target=third_function)
  t1.start()
  t2.start()
  t3.start()

실행 결과:

$ ./threading_name.py

first_function is Starting 
second_function is Starting 
third_function is Starting 
third_function is Exiting 
second_function is Exiting 
first_function is Exiting

로깅 모듈과 함께 사용:

#!/usr/bin/env python3
# coding=utf-8

import logging
import threading
import time

logging.basicConfig(
  level=logging.DEBUG,
  format='[%(levelname)s] (%(threadName)-10s) %(message)s',
  )
  
def worker():
  logging.debug('Starting')
  time.sleep(2)
  logging.debug('Exiting')
  
def my_service():
  logging.debug('Starting')
  time.sleep(3)
  logging.debug('Exiting')
  
t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name
w.start()
w2.start()
t.start()

실행 결과:

$ ./threading_names_log.py[DEBUG] (worker  ) Starting

[DEBUG] (Thread-1 ) Starting
[DEBUG] (my_service) Starting
[DEBUG] (worker  ) Exiting
[DEBUG] (Thread-1 ) Exiting
[DEBUG] (my_service) Exiting


하위 클래스에서 스레드 사용

이전에는 스레드가 구조화된 프로그래밍 형태로 만들어졌습니다. threading.Thread 클래스를 통합하여 스레드를 생성할 수도 있습니다. Thread 클래스는 먼저 몇 가지 기본 초기화를 완료한 다음 run()을 호출합니다. run() 메소드는 생성자에 전달된 대상 함수를 호출합니다.

#!/usr/bin/env python3
# coding=utf-8

import logging
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
  def __init__(self, threadID, name, counter):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.counter = counter
    
  def run(self):
    print ("Starting " + self.name)
    print_time(self.name, self.counter, 5)
    print ("Exiting " + self.name)
    
def print_time(threadName, delay, counter):
  while counter:
    if exitFlag:
      thread.exit()
    time.sleep(delay)
    print ("%s: %s" %(threadName, time.ctime(time.time())))
    counter -= 1
    
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print ("Exiting Main Thread")

실행 결과:

$ ./threading_subclass.py

Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Tue Sep 15 11:03:21 2015
Thread-2: Tue Sep 15 11:03:22 2015
Thread-1: Tue Sep 15 11:03:22 2015
Thread-1: Tue Sep 15 11:03:23 2015
Thread-2: Tue Sep 15 11:03:24 2015
Thread-1: Tue Sep 15 11:03:24 2015
Thread-1: Tue Sep 15 11:03:25 2015
Exiting Thread-1
Thread-2: Tue Sep 15 11:03:26 2015
Thread-2: Tue Sep 15 11:03:28 2015
Thread-2: Tue Sep 15 11:03:30 2015
Exiting Thread-2

자세히 보기 Python의 스레딩 모듈을 통한 스레드 정의 및 호출과 관련된 기사는 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.