over 2 years ago

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

BARRIER = Barrier(5)

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.

    for _ in range(how_many):
        # Read from the sensor


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

counter = LockingCounter()
run_threads(worker, how_many, counter)
print('Counter should be %d, found %d' %
      (5 * how_many, counter.count))
← Effective Python 心得筆記: Item 36 Effective Python 心得筆記: Item 39 →
comments powered by Disqus