Foundations of Python Network Programming

(WallPaper) #1
Chapter 8 ■ CaChes and Message Queues

145

To keep the example in this section self-contained, Listing 8-3 tackles a simple problem that does not really need
a message queue: computing the value of p by using a simple, if inefficient, Monte Carlo method. The messaging
topology, which is the important thing, is shown in Figure 8-1. A bitsource routine produces strings of length 2n
consisting of ones and zeros. I will use the odd bits as an n-digit integer x coordinate and the even bits as an n-digit
integer y coordinate. Does this coordinate lie inside or outside the quarter-circle centered on the origin whose radius
is the maximum value that either of these integers could take?


Figure 8-1. The topology of the simple Monte Carlo estimate of p


Using a publish-subscribe topology, you build an audience of two listeners for these binary strings. The always_yes
listener will receive only digit strings starting with 00 and can therefore always push the answer Y because, if your two
coordinates both start with the digit zero, then the point must lie in the lower-left quadrant of the field and therefore
fall safely inside the circle. The other three possible patterns for the first two bits, however, must be processed by the
judge routine that does the real test. It must ask pythagoras to compute the sum-of-the-squares of the two integer
coordinates to determine whether the point that they name falls inside or outside the circle and push T or F to its
outgoing queue accordingly.
The tally routine at the bottom of the topology receives either the T or F produced for every generated random bit
pattern, and by comparing the number of T answers to the total number of T and F answers together, it can estimate
the value of p. Do a web search for monte carlo estimate of pi if you are curious about the math.
Listing 8-3 implements this five-worker topology, which it lets run for 30 seconds before letting the program exit.
It requires ØMQ, which you can most easily make available to Python by creating a virtual environment and then
typing the following:


$ pip install pyzmq


This package might already be installed if you are using an operating system that has packaged Python for you or
a stand-alone Python installation like Anaconda. In either case, Listing 8-3 will be able to run out of the box without
an import error.

Free download pdf