β

Effective Python 心得筆記: Item 37 and 38

Python Life 70 阅读

Use Threads for Blocking I/O, Avoid for Parallelism

Use Lock to Prevent Data Races in Threads

兩個條款在講 threading ,不過只有粗淺地帶過,沒特別的地方。

比較有趣的是 Barrier 這個 Python 3.2 才加進來的東西,以前要用 Semaphore 來做。

from threading import Barrier
from threading import Thread
from threading import Lock

class LockingCounter(object):
    def __init__(self):
        self.lock = Lock()
        self.count = 0

    def increment(self, offset):
        with self.lock:
            self.count += offset

class LockingCounter(object):
    def __init__(self):
        self.lock = Lock()
        self.count = 0

    def increment(self, offset):
        with self.lock:
            self.count += offset

def worker(sensor_index, how_many, counter):
    # I have a barrier in here so the workers synchronize
    # when they start counting, otherwise it's hard to get a race
    # because the overhead of starting a thread is high.
    BARRIER.wait()
    for _ in range(how_many):
        # Read from the sensor
        counter.increment(1)

def run_threads(func, how_many, counter):
    threads = []
    for i in range(5):
        args = (i, how_many, counter)
        thread = Thread(target=func, args=args)
        threads.append(thread)
        thread.start()
    for thread in threads:
        thread.join()

BARRIER = Barrier(5)
counter = LockingCounter()
run_threads(worker, how_many, counter)
print('Counter should be %d, found %d' %
      (5 * how_many, counter.count))
作者:Python Life
原文地址:Effective Python 心得筆記: Item 37 and 38, 感谢原作者分享。