이 튜토리얼에서는 Python의 멀티 스레딩에 대해 배웁니다. 한 번에 여러 작업을 수행하는 데 도움이 됩니다. Python에는 스레딩 이라는 모듈이 있습니다. 멀티태스킹용
목록의 요소 합계를 계산하는 동안 백그라운드에서 파일에 데이터를 기록하여 작동 방식을 확인합니다. 프로그램에 관련된 단계를 살펴보겠습니다.
-
스레딩 모듈을 가져옵니다.
-
threading.Thread를 상속하여 클래스 만들기 수업.
-
위 클래스의 run 메소드 안에 파일 코드를 작성하세요.
-
필요한 데이터를 초기화합니다.
-
목록에 있는 숫자의 합을 계산하는 코드를 작성하세요.
예
# importing the modules
import threading
# creating a class by inhering the threading.Thread base class
class MultiTask(threading.Thread):
def __init__(self, message, filename):
# invoking the Base class
threading.Thread.__init__(self)
# initializing the variables to class
self.message = message
self.filename = filename
# run method that invokes in background
def run(self):
# opening the file in write mode
with open(filename, 'w+') as file:
file.write(message)
print("Finished writing to a file in background")
# initial code
if __name__ == '__main__':
# initializing the variables
message = "We're from Tutorialspoint"
filename = "tutorialspoint.txt"
# instantiation of the above class for background writing
file_write = MultiTask(message, filename)
# starting the task in background
file_write.start()
# another task
print("It will run parallelly to the above task")
nums = [1, 2, 3, 4, 5]
print(f"Sum of numbers 1-5: {sum(nums)}")
# completing the background task
file_write.join() 위의 작업과 병렬로 실행됩니다.
숫자 1-5의 합:15
백그라운드에서 파일 쓰기 완료
출력
파일의 디렉토리를 확인할 수 있습니다. 위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
It will run parallelly to the above task Sum of numbers 1-5: 15 Finished writing to a file in background
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.