Subclassing Processes

Python multiprocessing.

SU

Process sinfini o‘zlashtirish

multiprocessing modulidagi Process sinfini o‘zlashtirish (subclassing) ham mumkin. Bu threading.Thread sinfini o‘zlashtirishga juda o‘xshash tarzda ishlaydi.

Keling, misolni ko‘rib chiqamiz:

# worker_thread_subclass.py
 
import random
import multiprocessing
import time
 
class WorkerProcess(multiprocessing.Process):
 
    def __init__(self, name):
        multiprocessing.Process.__init__(self)
        self.name = name
 
    def run(self):
        """
        Protsessni ishga tushirish
        """
        worker(self.name)
 
def worker(name: str) -> None:
    print(f'Started worker {name}')
    worker_time = random.choice(range(1, 5))
    time.sleep(worker_time)
    print(f'{name} worker finished in {worker_time} seconds')
 
if __name__ == '__main__':
    processes = []
    for i in range(5):
        process = WorkerProcess(name=f'computer_{i}')
        processes.append(process)
        process.start()
 
    for process in processes:
        process.join()

Ushbu kod tanish ko‘rinishi kerak. WorkerProcess sinfi oldingi bobdagi WorkerThread sinfiga aynan o‘xshash, faqat bu safar Thread o‘rniga Process sinfi o‘zlashtirilmoqda.

Asosiy farq:

  • 28-qator: Bu yerda siz sinfni yaratib, protsessni ishga tushirishingiz va uni protsesslar ro‘yxatiga qo‘shishingiz kerak.
  • Keyin protsesslar ro‘yxatidan o‘tib, har bir protsessga join() chaqiriladi. Bu protsesslarning to‘g‘ri ishlashi uchun zarur.

Bu usul avvalgi misolda ko‘rilgan protsesslar bilan ishlashga juda o‘xshash.

Chiqish:

Ushbu sinfdan olingan natija oldingi bo‘limdagi protsess misolining chiqishiga juda o‘xshash bo‘ladi.

Started worker computer_0
Started worker computer_1
Started worker computer_2
Started worker computer_3
Started worker computer_4
computer_2 worker finished in 2 seconds
computer_1 worker finished in 3 seconds
computer_3 worker finished in 3 seconds
computer_0 worker finished in 4 seconds
computer_4 worker finished in 4 seconds

Har safar kodni ishga tushirganingizda, random modulining ishlashi tufayli natijalar biroz farq qilishi mumkin.

Last updated on

On this page

Xato haqida xabar berish