Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonでマルチスレッドキューを実装する方法


はじめに..

この例では、実行するすべてのタスクを保持するタスクキューと、キューと相互作用してその要素を個別に処理するスレッドプールを作成します。

まず、キューとは何ですか?という質問から始めます。キューは、非常に特定の順序で維持されるさまざまな要素のコレクションであるデータ構造です。実際の例を挙げて説明しましょう。

食料品店のカウンターで食料品の請求書を支払うために並んでいると仮定します(どの食料品店か私に聞かないでください)

請求書の支払いを待っている人々の列の中で、次のことに気付くでしょう:

1.人々はラインの一方の端から入り、もう一方の端から出ます。

2.人物Aが人物Bの前に列に入る場合、人物Aは人物Bの前に列を離れます(人物Bが有名人であるか、優先度が高い場合を除く)。

3.全員が請求書を支払うと、列に誰も残りません。

さて、キューが同じように機能するプログラミングに戻りましょう。

1.エンキュー-キューの最後に追加された要素。

2.デキュー-キューの先頭から削除された要素。

さらに、先入れ先出し(FIFO)-最初に追加された要素が最初に削除されます。後入れ先出し(LIFO)-追加された最後の要素が最初に削除されます。

Pythonはキューデータ構造をどのように実装しますか?

Pythonのキューモジュールは、キューデータ構造の簡単な実装を提供します。各キューには次のメソッドがあります。

  • get():次の要素を返します。

  • put():新しい要素を追加します。

  • qsize():キュー内の現在の要素の数。

  • empty():キューが空かどうかを示すブール値を返します。

  • full():キューがいっぱいかどうかを示すブール値を返します。

1.引数xを取り、1とそれ自体(x)の間の数値を反復処理して、乗算を実行する関数を作成します。たとえばこの関数に5を渡すと、1から5まで繰り返し、乗算を続けます。つまり、1 x 5、2 x 5、3 x 5、4 x 5、5 x 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つのキューに入れられ、請求書の支払いを完了した人は列を離れて次の人に道を譲ります。


  1. Bokeh(Python)で画像を操作する方法は?

    Bokehで画像を操作するには、 image_url()を使用します メソッドと画像のリストを渡します。 ステップ :func:show のときにファイルに保存された出力を生成するように、デフォルトの出力状態を構成します と呼ばれます。 プロット用の新しい図を作成します。 指定されたURLから読み込まれた画像をレンダリングします。 Bokehオブジェクトまたはアプリケーションをすぐに表示します。 例 from bokeh.plotting import figure, show, output_file output_file('image.html') p = fi

  2. PythonでAPIの結果を視覚化する方法

    はじめに.. APIを作成する最大の利点の1つは、現在/ライブのデータを抽出することです。データが急速に変化している場合でも、APIは常に最新のデータを取得します。 APIプログラムは、非常に具体的なURLを使用して、特定の情報を要求します。 SpotifyまたはYoutubeMusicで2020年に最も再生された100曲をToppします。リクエストされたデータは、JSONやCSVなどの簡単に処理できる形式で返されます。 Pythonを使用すると、ユーザーは考えられるほぼすべてのURLにAPI呼び出しを記述できます。この例では、GitHubからAPIの結果を抽出して視覚化する方法を示します