@@ -1482,21 +1482,22 @@ of the derived iterators.
14821482
14831483 import threading
14841484
1485- def count ( ):
1486- for i in range (5 ):
1487- yield i
1485+ def squares ( n ):
1486+ for x in range (n ):
1487+ yield x * x
14881488
1489- it = threading.serialize_iterator(count())
1489+ def consume (name , iterable ):
1490+ for item in iterable:
1491+ print (name, item)
14901492
1491- def worker ():
1492- for item in it:
1493- print (threading.current_thread().name, item)
1493+ source = threading.serialize_iterator(squares(5 ))
14941494
1495- threads = [threading.Thread(target = worker) for _ in range (2 )]
1496- for thread in threads:
1497- thread.start()
1498- for thread in threads:
1499- thread.join()
1495+ t1 = threading.Thread(target = consume, args = (" left" , source))
1496+ t2 = threading.Thread(target = consume, args = (" right" , source))
1497+ t1.start()
1498+ t2.start()
1499+ t1.join()
1500+ t2.join()
15001501
15011502 In this example, each number is printed exactly once, but the work is shared
15021503 between the two threads.
@@ -1519,23 +1520,22 @@ of the derived iterators.
15191520 import threading
15201521
15211522 @threading.synchronized_iterator
1522- def counter ():
1523- i = 0
1524- while True :
1525- yield i
1526- i += 1
1523+ def squares (n ):
1524+ for x in range (n):
1525+ yield x * x
15271526
1528- it = counter()
1527+ def consume (name , iterable ):
1528+ for item in iterable:
1529+ print (name, item)
15291530
1530- def worker ():
1531- for _ in range (5 ):
1532- print (next (it))
1531+ source = squares(5 )
15331532
1534- threads = [threading.Thread(target = worker) for _ in range (2 )]
1535- for thread in threads:
1536- thread.start()
1537- for thread in threads:
1538- thread.join()
1533+ t1 = threading.Thread(target = consume, args = (" left" , source))
1534+ t2 = threading.Thread(target = consume, args = (" right" , source))
1535+ t1.start()
1536+ t2.start()
1537+ t1.join()
1538+ t2.join()
15391539
15401540 The returned wrapper preserves the metadata of *func *, such as its name and
15411541 wrapped function reference.
@@ -1570,13 +1570,17 @@ of the derived iterators.
15701570
15711571 import threading
15721572
1573- source = (x** 2 for x in range (5 ))
1574- left, right = threading.concurrent_tee(source)
1573+ def squares (n ):
1574+ for x in range (n):
1575+ yield x * x
15751576
15761577 def consume (name , iterable ):
15771578 for item in iterable:
15781579 print (name, item)
15791580
1581+ source = squares(5 )
1582+ left, right = threading.concurrent_tee(source)
1583+
15801584 t1 = threading.Thread(target = consume, args = (" left" , left))
15811585 t2 = threading.Thread(target = consume, args = (" right" , right))
15821586 t1.start()
0 commit comments