If you feel that examples of threads from Threads (Part I) isn’t too complex for you, today I bring you a better example (and well known). The producer-consumer example
. This example, for the people that don’t know the case, is based in two actors, one that produces something (numbers in this case) and other that consumes them. This a typical concurrent example, and this is the python version:
from threading import Thread, Lock array = [] myLock = Lock () elements = 10 class Producer (Thread): def run (self): for i in range (elements): myLock.acquire () array.append (i) myLock.release () print '-> Produced %d' % i class Consumer (Thread): def run (self): consumed = 0 while consumed < elements: myLock.acquire () if len (array) > 0: e = array[0] del array[0] myLock.release () print '<- Consumed %d' % e consumed += 1 if __name__ == '__main__': p1 = Producer () p2 = Producer () c1 = Consumer () c2 = Consumer () p1.start () c1.start () p2.start () c2.start () p1.join () p2.join () c1.join () c2.join ()
First, you see some variable declaration, including a declaration for a Lock in order to make correct access to the shared variable array. Then two classes are defined, the main classes, one for the producer and another for the consumer. At the end, in the main program, we create two producers and two consumers and they’re running until the end of their lives. For thread right end, you must join all instances. The output showed by this script is:
-> Produced 0 -> Produced 1 -> Produced 2 -> Produced 3 -> Produced 4 -> Produced 5 -> Produced 6 -> Produced 7 -> Produced 8 <- Consumed 0 <- Consumed 1 <- Consumed 2 -> Produced 9 <- Consumed 3 <- Consumed 4 <- Consumed 5 <- Consumed 6 <- Consumed 7 -> Produced 0 -> Produced 1 -> Produced 2 <- Consumed 8 <- Consumed 9 -> Produced 3 -> Produced 4 -> Produced 5 -> Produced 6 -> Produced 7 <- Consumed 0 <- Consumed 1 <- Consumed 2 <- Consumed 3 <- Consumed 4 -> Produced 8 -> Produced 9 <- Consumed 5 <- Consumed 6 <- Consumed 7 <- Consumed 8 <- Consumed 9
This is all for now, stay tuned for more snippets
. See you!