Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python으로 다중 스레드 대기열을 구현하는 방법

<시간/>

소개..

이 예에서는 실행할 모든 작업을 보관하는 작업 대기열과 해당 요소를 개별적으로 처리하기 위해 대기열과 상호 작용하는 스레드 풀을 만듭니다.

대기열이란 무엇입니까?라는 질문으로 시작하겠습니다. 큐는 매우 특정한 순서로 유지되는 다양한 요소의 모음인 데이터 구조입니다. 실생활의 예를 들어 설명하겠습니다.

식료품점 카운터에 식료품 청구서를 지불하기 위해 줄을 서 있다고 가정합니다. (어느 식료품점인지 묻지 마십시오)

청구서 지불을 기다리는 사람들의 줄에서 다음을 볼 수 있습니다.

1. 사람들은 줄의 한쪽 끝으로 들어갔다가 다른 쪽 끝으로 나옵니다.

2. A가 B보다 먼저 입장하면 A가 B보다 먼저 입장합니다(B가 연예인이거나 우선순위가 높은 경우는 제외).

3. 모든 사람이 청구서를 지불하면 줄에 아무도 남지 않습니다.

큐가 비슷한 방식으로 작동하는 프로그래밍으로 돌아갑니다.

1. enqueue - 대기열의 끝에 추가된 요소입니다.

2. dequeue - 대기열의 시작 부분에서 제거된 요소입니다.

더 많은 것이 FIFO(선입 선출)입니다. 먼저 추가된 요소가 먼저 제거됩니다. LIFO(후입선출) - 마지막에 추가된 요소가 먼저 제거됩니다.

Python은 큐 데이터 구조를 어떻게 구현합니까?

Python의 대기열 모듈은 대기열 데이터 구조의 간단한 구현을 제공합니다. 각 대기열에는 다음과 같은 메서드가 있을 수 있습니다.

  • get():다음 요소를 반환합니다.

  • put():새 요소를 추가합니다.

  • qsize():큐에 있는 현재 요소의 수.

  • empty():큐가 비어 있는지 여부를 나타내는 부울을 반환합니다.

  • full():큐가 가득 찼는지 여부를 나타내는 부울을 반환합니다.

1. 인수 x를 취한 다음 1과 자체(x) 사이의 숫자를 반복하여 곱셈을 수행하는 함수를 만들 것입니다. 예를 들어 이 함수에 5를 전달하면 1에서 5까지 반복하고 계속해서 곱합니다. 즉 1 곱하기 5, 2 곱하기 5, 3 곱하기 5, 4 곱하기 5, 5 곱하기 5 마지막으로 값을 목록으로 반환합니다.

예시

def print_multiply(x):
output_value = []
for i in range(1, x + 1):
output_value.append(i * x)
print(f"Output \n *** The multiplication result for the {x} is - {output_value}")
print_multiply(5)
입니다.

출력

*** The multiplication result for the 5 is - [5, 10, 15, 20, 25]

2. 우리는 큐 객체의 다음 요소를 얻으려고 시도하는 process_queue()라는 또 다른 함수를 작성할 것입니다. 이 매우 간단한 논리는 큐가 비어 있을 때까지 요소를 계속 전달합니다. 진행을 조금 늦추기 위해 절전 모드를 사용하겠습니다.

예시

def process_queue():
while True:
try:
value = my_queue.get(block=False)
except queue.Empty:
return
else:
print_multiply(value)
time.sleep(2)

3. 클래스를 생성합니다. 새로운 인스턴스가 초기화되고 시작될 때 process_queue() 함수가 호출됩니다.

예시

class MultiThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name

def run(self):
print(f" ** Starting the thread - {self.name}")
process_queue()
print(f" ** Completed the thread - {self.name}")

4.마지막으로 입력된 숫자 목록을 전달하고 대기열을 채웁니다.

# setting up variables
input_values = [5, 10, 15, 20]

# fill the queue
my_queue = queue.Queue()
for x in input_values:
my_queue.put(x)

5.마지막으로, 모든 것을 합친다.

import queue
import threading
import time

# Class
class MultiThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name

def run(self):
print(f"Output \n ** Starting the thread - {self.name}")
process_queue()
print(f" ** Completed the thread - {self.name}")

# Process thr queue
def process_queue():
while True:
try:
value = my_queue.get(block=False)
except queue.Empty:
return
else:
print_multiply(value)
time.sleep(2)

# function to multiply
def print_multiply(x):
output_value = []
for i in range(1, x + 1):
output_value.append(i * x)
print(f" \n *** The multiplication result for the {x} is - {output_value}")

# Input variables
input_values = [2, 4, 6, 5,10,3]

# fill the queue
my_queue = queue.Queue()
for x in input_values:
my_queue.put(x)
# initializing and starting 3 threads
thread1 = MultiThread('First')
thread2 = MultiThread('Second')
thread3 = MultiThread('Third')
thread4 = MultiThread('Fourth')

# Start the threads
thread1.start()
thread2.start()
thread3.start()
thread4.start()

# Join the threads
thread1.join()
thread2.join()
thread3.join()
thread4.join()

출력

** Starting the thread - First
*** The multiplication result for the 2 is - [2, 4]

출력

** Starting the thread - Second
*** The multiplication result for the 4 is - [4, 8, 12, 16]

출력

** Starting the thread - Third
*** The multiplication result for the 6 is - [6, 12, 18, 24, 30, 36]

출력

** Starting the thread - Fourth
*** The multiplication result for the 5 is - [5, 10, 15, 20, 25]
*** The multiplication result for the 10 is - [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
*** The multiplication result for the 3 is - [3, 6, 9] ** Completed the thread - Third
** Completed the thread - Fourth
** Completed the thread - Second ** Completed the thread - First

6. 대기열 개념을 성공적으로 구현했습니다. 4개의 스레드가 있지만 처리할 값이 6개이므로 대기열에 먼저 오는 사람이 실행되고 다른 사람이 다른 사람이 완료될 때까지 줄을 서서 기다려야 합니다.

이것은 실제 생활과 유사합니다. 계산대가 3개 있지만 10명이 청구서를 지불하기 위해 기다리고 있다고 가정하면 10명이 3개의 대기열에 있고 청구서를 완료한 사람이 줄을 서서 다음 사람을 위해 자리를 비웁니다.