sharemem.xml 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. <codewalk title="Share Memory By Communicating">
  2. <step title="Introduction" src="doc/codewalk/urlpoll.go">
  3. Go's approach to concurrency differs from the traditional use of
  4. threads and shared memory. Philosophically, it can be summarized:
  5. <br/><br/>
  6. <i>Don't communicate by sharing memory; share memory by communicating.</i>
  7. <br/><br/>
  8. Channels allow you to pass references to data structures between goroutines.
  9. If you consider this as passing around ownership of the data (the ability to
  10. read and write it), they become a powerful and expressive synchronization
  11. mechanism.
  12. <br/><br/>
  13. In this codewalk we will look at a simple program that polls a list of
  14. URLs, checking their HTTP response codes and periodically printing their state.
  15. </step>
  16. <step title="State type" src="doc/codewalk/urlpoll.go:/State/,/}/">
  17. The State type represents the state of a URL.
  18. <br/><br/>
  19. The Pollers send State values to the StateMonitor,
  20. which maintains a map of the current state of each URL.
  21. </step>
  22. <step title="Resource type" src="doc/codewalk/urlpoll.go:/Resource/,/}/">
  23. A Resource represents the state of a URL to be polled: the URL itself
  24. and the number of errors encountered since the last successful poll.
  25. <br/><br/>
  26. When the program starts, it allocates one Resource for each URL.
  27. The main goroutine and the Poller goroutines send the Resources to
  28. each other on channels.
  29. </step>
  30. <step title="Poller function" src="doc/codewalk/urlpoll.go:/func Poller/,/\n}/">
  31. Each Poller receives Resource pointers from an input channel.
  32. In this program, the convention is that sending a Resource pointer on
  33. a channel passes ownership of the underlying data from the sender
  34. to the receiver. Because of this convention, we know that
  35. no two goroutines will access this Resource at the same time.
  36. This means we don't have to worry about locking to prevent concurrent
  37. access to these data structures.
  38. <br/><br/>
  39. The Poller processes the Resource by calling its Poll method.
  40. <br/><br/>
  41. It sends a State value to the status channel, to inform the StateMonitor
  42. of the result of the Poll.
  43. <br/><br/>
  44. Finally, it sends the Resource pointer to the out channel. This can be
  45. interpreted as the Poller saying &quot;I'm done with this Resource&quot; and
  46. returning ownership of it to the main goroutine.
  47. <br/><br/>
  48. Several goroutines run Pollers, processing Resources in parallel.
  49. </step>
  50. <step title="The Poll method" src="doc/codewalk/urlpoll.go:/Poll executes/,/\n}/">
  51. The Poll method (of the Resource type) performs an HTTP HEAD request
  52. for the Resource's URL and returns the HTTP response's status code.
  53. If an error occurs, Poll logs the message to standard error and returns the
  54. error string instead.
  55. </step>
  56. <step title="main function" src="doc/codewalk/urlpoll.go:/func main/,/\n}/">
  57. The main function starts the Poller and StateMonitor goroutines
  58. and then loops passing completed Resources back to the pending
  59. channel after appropriate delays.
  60. </step>
  61. <step title="Creating channels" src="doc/codewalk/urlpoll.go:/Create our/,/complete/">
  62. First, main makes two channels of *Resource, pending and complete.
  63. <br/><br/>
  64. Inside main, a new goroutine sends one Resource per URL to pending
  65. and the main goroutine receives completed Resources from complete.
  66. <br/><br/>
  67. The pending and complete channels are passed to each of the Poller
  68. goroutines, within which they are known as in and out.
  69. </step>
  70. <step title="Initializing StateMonitor" src="doc/codewalk/urlpoll.go:/Launch the StateMonitor/,/statusInterval/">
  71. StateMonitor will initialize and launch a goroutine that stores the state
  72. of each Resource. We will look at this function in detail later.
  73. <br/><br/>
  74. For now, the important thing to note is that it returns a channel of State,
  75. which is saved as status and passed to the Poller goroutines.
  76. </step>
  77. <step title="Launching Poller goroutines" src="doc/codewalk/urlpoll.go:/Launch some Poller/,/}/">
  78. Now that it has the necessary channels, main launches a number of
  79. Poller goroutines, passing the channels as arguments.
  80. The channels provide the means of communication between the main, Poller, and
  81. StateMonitor goroutines.
  82. </step>
  83. <step title="Send Resources to pending" src="doc/codewalk/urlpoll.go:/Send some Resources/,/}\(\)/">
  84. To add the initial work to the system, main starts a new goroutine
  85. that allocates and sends one Resource per URL to pending.
  86. <br/><br/>
  87. The new goroutine is necessary because unbuffered channel sends and
  88. receives are synchronous. That means these channel sends will block until
  89. the Pollers are ready to read from pending.
  90. <br/><br/>
  91. Were these sends performed in the main goroutine with fewer Pollers than
  92. channel sends, the program would reach a deadlock situation, because
  93. main would not yet be receiving from complete.
  94. <br/><br/>
  95. Exercise for the reader: modify this part of the program to read a list of
  96. URLs from a file. (You may want to move this goroutine into its own
  97. named function.)
  98. </step>
  99. <step title="Main Event Loop" src="doc/codewalk/urlpoll.go:/range complete/,/\n }/">
  100. When a Poller is done with a Resource, it sends it on the complete channel.
  101. This loop receives those Resource pointers from complete.
  102. For each received Resource, it starts a new goroutine calling
  103. the Resource's Sleep method. Using a new goroutine for each
  104. ensures that the sleeps can happen in parallel.
  105. <br/><br/>
  106. Note that any single Resource pointer may only be sent on either pending or
  107. complete at any one time. This ensures that a Resource is either being
  108. handled by a Poller goroutine or sleeping, but never both simultaneously.
  109. In this way, we share our Resource data by communicating.
  110. </step>
  111. <step title="The Sleep method" src="doc/codewalk/urlpoll.go:/Sleep/,/\n}/">
  112. Sleep calls time.Sleep to pause before sending the Resource to done.
  113. The pause will either be of a fixed length (pollInterval) plus an
  114. additional delay proportional to the number of sequential errors (r.errCount).
  115. <br/><br/>
  116. This is an example of a typical Go idiom: a function intended to run inside
  117. a goroutine takes a channel, upon which it sends its return value
  118. (or other indication of completed state).
  119. </step>
  120. <step title="StateMonitor" src="doc/codewalk/urlpoll.go:/StateMonitor/,/\n}/">
  121. The StateMonitor receives State values on a channel and periodically
  122. outputs the state of all Resources being polled by the program.
  123. </step>
  124. <step title="The updates channel" src="doc/codewalk/urlpoll.go:/updates :=/">
  125. The variable updates is a channel of State, on which the Poller goroutines
  126. send State values.
  127. <br/><br/>
  128. This channel is returned by the function.
  129. </step>
  130. <step title="The urlStatus map" src="doc/codewalk/urlpoll.go:/urlStatus/">
  131. The variable urlStatus is a map of URLs to their most recent status.
  132. </step>
  133. <step title="The Ticker object" src="doc/codewalk/urlpoll.go:/ticker/">
  134. A time.Ticker is an object that repeatedly sends a value on a channel at a
  135. specified interval.
  136. <br/><br/>
  137. In this case, ticker triggers the printing of the current state to
  138. standard output every updateInterval nanoseconds.
  139. </step>
  140. <step title="The StateMonitor goroutine" src="doc/codewalk/urlpoll.go:/go func/,/}\(\)/">
  141. StateMonitor will loop forever, selecting on two channels:
  142. ticker.C and update. The select statement blocks until one of its
  143. communications is ready to proceed.
  144. <br/><br/>
  145. When StateMonitor receives a tick from ticker.C, it calls logState to
  146. print the current state. When it receives a State update from updates,
  147. it records the new status in the urlStatus map.
  148. <br/><br/>
  149. Notice that this goroutine owns the urlStatus data structure,
  150. ensuring that it can only be accessed sequentially.
  151. This prevents memory corruption issues that might arise from parallel reads
  152. and/or writes to a shared map.
  153. </step>
  154. <step title="Conclusion" src="doc/codewalk/urlpoll.go">
  155. In this codewalk we have explored a simple example of using Go's concurrency
  156. primitives to share memory through communication.
  157. <br/><br/>
  158. This should provide a starting point from which to explore the ways in which
  159. goroutines and channels can be used to write expressive and concise concurrent
  160. programs.
  161. </step>
  162. </codewalk>