Temat 10: Przetwarzanie równoległe (I)

Wstecz; Ostatnia modyfikacja: 6.05.2015
  • Standardowe biblioteki wspierające wielowątkowość i wieloprocesowość w Pythonie: threading oraz multiprocessing
  • Procesy (ang. processes) posiadają, między innymi:
    • systemowy identyfkator procesu (PID)
    • wirtualną przestrzeń adresową
    • wykonywalny kod maszynowy
    • przynajmniej jeden wątek wykonania
  • Wątki (ang. thread)
    • jednostki wykonania programu wewnątrz procesu
    • wątki współdzielą przestrzeń adresową procesu
    • Implementacja wątków w module threading ogranicza wykonianie programu do tylko jednego wątku na raz!
      "CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously."
  • Przykład programu z wieloma wątkami
  • 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"
    
  • Przykład programu z wieloma procesami
  • from multiprocessing import Pool
    
    def f(x):
        return x*x
    
    if __name__ == '__main__':
        pool = Pool(processes=4)
        result = pool.apply_async(f, [10])  
        print result.get(timeout=1)
        print pool.map(f, range(10))
    
  • Ćwiczenie 1: przetestuj szybkość działania powyższego programu (oraz nieco zmodyfikowanych wersji) w zależności od liczby wykorzystywanych wątków / procesów. Zbadaj obciążenie procesora wykananiem badanych programów. Ile rdzeni jest wykorzystywanych?
  • Ćwiczenie 2: napisz program "runblastmulti.py", który wyszukuje zadaną sekwencję białkową w tych bazach danych BLAST używając programu blastp lub psiblast, ale na zadanej liczbie procesów. Wykorzystaj bibliotekę multiprocessing.