intro.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
  7. <title>Introduction</title>
  8. <link rel="stylesheet" href="html4css1.css" type="text/css" />
  9. </head>
  10. <body>
  11. <div class="header">
  12. <a class="reference" href="index.html">Prev</a> &nbsp; &nbsp; &nbsp; &nbsp; <a class="reference" href="index.html">Up</a> &nbsp; &nbsp; &nbsp; &nbsp; <a class="reference" href="processing-ref.html">Next</a>
  13. <hr class="header"/>
  14. </div>
  15. <div class="document" id="introduction">
  16. <h1 class="title">Introduction</h1>
  17. <div class="section">
  18. <h1><a id="threads-processes-and-the-gil" name="threads-processes-and-the-gil">Threads, processes and the GIL</a></h1>
  19. <p>To run more than one piece of code at the same time on the same
  20. computer one has the choice of either using multiple processes or
  21. multiple threads.</p>
  22. <p>Although a program can be made up of multiple processes, these
  23. processes are in effect completely independent of one another:
  24. different processes are not able to cooperate with one another unless
  25. one sets up some means of communication between them (such as by using
  26. sockets). If a lot of data must be transferred between processes then
  27. this can be inefficient.</p>
  28. <p>On the other hand, multiple threads within a single process are
  29. intimately connected: they share their data but often can interfere
  30. badly with one another. It is often argued that the only way to make
  31. multithreaded programming &quot;easy&quot; is to avoid relying on any shared
  32. state and for the threads to only communicate by passing messages to
  33. each other.</p>
  34. <p>CPython has a <em>Global Interpreter Lock</em> (GIL) which in many ways makes
  35. threading easier than it is in most languages by making sure that only
  36. one thread can manipulate the interpreter's objects at a time. As a
  37. result, it is often safe to let multiple threads access data without
  38. using any additional locking as one would need to in a language such
  39. as C.</p>
  40. <p>One downside of the GIL is that on multi-processor (or multi-core)
  41. systems a multithreaded Python program can only make use of one
  42. processor at a time. This is a problem that can be overcome by using
  43. multiple processes instead.</p>
  44. <p>Python gives little direct support for writing programs using multiple
  45. process. This package allows one to write multi-process programs
  46. using much the same API that one uses for writing threaded programs.</p>
  47. </div>
  48. <div class="section">
  49. <h1><a id="forking-and-spawning" name="forking-and-spawning">Forking and spawning</a></h1>
  50. <p>There are two ways of creating a new process in Python:</p>
  51. <ul>
  52. <li><p class="first">The current process can <em>fork</em> a new child process by using the
  53. <tt class="docutils literal"><span class="pre">os.fork()</span></tt> function. This effectively creates an identical copy
  54. of the current process which is now able to go off and perform some
  55. task set by the parent process. This means that the child process
  56. inherits <em>copies</em> of all variables that the parent process had.</p>
  57. <p>However, <tt class="docutils literal"><span class="pre">os.fork()</span></tt> is not available on every platform: in
  58. particular Windows does not support it.</p>
  59. </li>
  60. <li><p class="first">Alternatively, the current process can spawn a completely new Python
  61. interpreter by using the <tt class="docutils literal"><span class="pre">subprocess</span></tt> module or one of the
  62. <tt class="docutils literal"><span class="pre">os.spawn*()</span></tt> functions.</p>
  63. <p>Getting this new interpreter in to a fit state to perform the task
  64. set for it by its parent process is, however, a bit of a challenge.</p>
  65. </li>
  66. </ul>
  67. <p>The <tt class="docutils literal"><span class="pre">processing</span></tt> package uses <tt class="docutils literal"><span class="pre">os.fork()</span></tt> if it is available since
  68. it makes life a lot simpler. Forking the process is also more
  69. efficient in terms of memory usage and the time needed to create the
  70. new process.</p>
  71. </div>
  72. <div class="section">
  73. <h1><a id="the-process-class" name="the-process-class">The Process class</a></h1>
  74. <p>In the <tt class="docutils literal"><span class="pre">processing</span></tt> package processes are spawned by creating a
  75. <tt class="docutils literal"><span class="pre">Process</span></tt> object and then calling its <tt class="docutils literal"><span class="pre">start()</span></tt> method.
  76. <tt class="docutils literal"><span class="pre">processing.Process</span></tt> follows the API of <tt class="docutils literal"><span class="pre">threading.Thread</span></tt>. A
  77. trivial example of a multiprocess program is</p>
  78. <pre class="literal-block">
  79. from processing import Process
  80. def f(name):
  81. print 'hello', name
  82. if __name__ == '__main__':
  83. p = Process(target=f, args=('bob',))
  84. p.start()
  85. p.join()
  86. </pre>
  87. <p>Here the function <tt class="docutils literal"><span class="pre">f</span></tt> is run in a child process.</p>
  88. <p>For an explanation of why (on Windows) the <tt class="docutils literal"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></tt>
  89. part is necessary see <a class="reference" href="programming-guidelines.html">Programming guidelines</a>.</p>
  90. </div>
  91. <div class="section">
  92. <h1><a id="exchanging-objects-between-processes" name="exchanging-objects-between-processes">Exchanging objects between processes</a></h1>
  93. <p><tt class="docutils literal"><span class="pre">processing</span></tt> supports two types of communication channel between
  94. processes:</p>
  95. <dl class="docutils">
  96. <dt><strong>Queues</strong>:</dt>
  97. <dd><p class="first">The function <tt class="docutils literal"><span class="pre">Queue()</span></tt> returns a near clone of <tt class="docutils literal"><span class="pre">Queue.Queue</span></tt>
  98. -- see the Python standard documentation. For example</p>
  99. <pre class="literal-block">
  100. from processing import Process, Queue
  101. def f(q):
  102. q.put([42, None, 'hello'])
  103. if __name__ == '__main__':
  104. q = Queue()
  105. p = Process(target=f, args=(q,))
  106. p.start()
  107. print q.get() # prints &quot;[42, None, 'hello']&quot;
  108. p.join()
  109. </pre>
  110. <p class="last">Queues are thread and process safe. See <a class="reference" href="processing-ref.html#pipes-and-queues">Queues</a>.</p>
  111. </dd>
  112. <dt><strong>Pipes</strong>:</dt>
  113. <dd><p class="first">The <tt class="docutils literal"><span class="pre">Pipe()</span></tt> function returns a pair of connection objects
  114. connected by a pipe which by default is duplex (two-way). For
  115. example</p>
  116. <pre class="literal-block">
  117. from processing import Process, Pipe
  118. def f(conn):
  119. conn.send([42, None, 'hello'])
  120. conn.close()
  121. if __name__ == '__main__':
  122. parent_conn, child_conn = Pipe()
  123. p = Process(target=f, args=(child_conn,))
  124. p.start()
  125. print parent_conn.recv() # prints &quot;[42, None, 'hello']&quot;
  126. p.join()
  127. </pre>
  128. <p class="last">The two connection objects returned by <tt class="docutils literal"><span class="pre">Pipe()</span></tt> represent the two
  129. ends of the pipe. Each connection object has <tt class="docutils literal"><span class="pre">send()</span></tt> and
  130. <tt class="docutils literal"><span class="pre">recv()</span></tt> methods (among others). Note that data in a pipe may
  131. become corrupted if two processes (or threads) try to read from or
  132. write to the <em>same</em> end of the pipe at the same time. Of course
  133. there is no risk of corruption from processes using different ends
  134. of the pipe at the same time. See <a class="reference" href="processing-ref.html#pipes-and-queues">Pipes</a>.</p>
  135. </dd>
  136. </dl>
  137. </div>
  138. <div class="section">
  139. <h1><a id="synchronization-between-processes" name="synchronization-between-processes">Synchronization between processes</a></h1>
  140. <p><tt class="docutils literal"><span class="pre">processing</span></tt> contains equivalents of all the synchronization
  141. primitives from <tt class="docutils literal"><span class="pre">threading</span></tt>. For instance one can use a lock to
  142. ensure that only one process prints to standard output at a time:</p>
  143. <pre class="literal-block">
  144. from processing import Process, Lock
  145. def f(l, i):
  146. l.acquire()
  147. print 'hello world', i
  148. l.release()
  149. if __name__ == '__main__':
  150. lock = Lock()
  151. for num in range(10):
  152. Process(target=f, args=(lock, num)).start()
  153. </pre>
  154. <p>Without using the lock output from the different processes is liable
  155. to get all mixed up.</p>
  156. </div>
  157. <div class="section">
  158. <h1><a id="sharing-state-between-processes" name="sharing-state-between-processes">Sharing state between processes</a></h1>
  159. <p>As mentioned above, when doing concurrent programming it is usually
  160. best to avoid using shared state as far as possible. This is
  161. particularly true when using multiple processes.</p>
  162. <p>However, if you really do need to use some shared data then
  163. <tt class="docutils literal"><span class="pre">processing</span></tt> provides a couple of ways of doing so.</p>
  164. <dl class="docutils">
  165. <dt><strong>Shared memory</strong>:</dt>
  166. <dd><p class="first">Data can be stored in a shared memory map using <tt class="docutils literal"><span class="pre">Value</span></tt> or <tt class="docutils literal"><span class="pre">Array</span></tt>.
  167. For example the following code</p>
  168. <pre class="literal-block">
  169. from processing import Process, Value, Array
  170. def f(n, a):
  171. n.value = 3.1415927
  172. for i in range(len(a)):
  173. a[i] = -a[i]
  174. if __name__ == '__main__':
  175. num = Value('d', 0.0)
  176. arr = Array('i', range(10))
  177. p = Process(target=f, args=(num, arr))
  178. p.start()
  179. p.join()
  180. print num.value
  181. print arr[:]
  182. </pre>
  183. <p>will print</p>
  184. <pre class="literal-block">
  185. 3.1415927
  186. [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
  187. </pre>
  188. <p>The <tt class="docutils literal"><span class="pre">'d'</span></tt> and <tt class="docutils literal"><span class="pre">'i'</span></tt> arguments used when creating <tt class="docutils literal"><span class="pre">num</span></tt> and <tt class="docutils literal"><span class="pre">arr</span></tt>
  189. are typecodes of the kind used by the <tt class="docutils literal"><span class="pre">array</span></tt> module: <tt class="docutils literal"><span class="pre">'d'</span></tt>
  190. indicates a double precision float and <tt class="docutils literal"><span class="pre">'i'</span></tt> inidicates a signed
  191. integer. These shared objects will be process and thread safe.</p>
  192. <p class="last">For more flexibility in using shared memory one can use the
  193. <tt class="docutils literal"><span class="pre">processing.sharedctypes</span></tt> module which supports the creation of
  194. arbitrary <a class="reference" href="sharedctypes.html">ctypes objects allocated from shared memory</a>.</p>
  195. </dd>
  196. <dt><strong>Server process</strong>:</dt>
  197. <dd><p class="first">A manager object returned by <tt class="docutils literal"><span class="pre">Manager()</span></tt> controls a server process
  198. which holds python objects and allows other processes to manipulate
  199. them using proxies.</p>
  200. <p>A manager returned by <tt class="docutils literal"><span class="pre">Manager()</span></tt> will support types <tt class="docutils literal"><span class="pre">list</span></tt>,
  201. <tt class="docutils literal"><span class="pre">dict</span></tt>, <tt class="docutils literal"><span class="pre">Namespace</span></tt>, <tt class="docutils literal"><span class="pre">Lock</span></tt>, <tt class="docutils literal"><span class="pre">RLock</span></tt>, <tt class="docutils literal"><span class="pre">Semaphore</span></tt>,
  202. <tt class="docutils literal"><span class="pre">BoundedSemaphore</span></tt>, <tt class="docutils literal"><span class="pre">Condition</span></tt>, <tt class="docutils literal"><span class="pre">Event</span></tt>, <tt class="docutils literal"><span class="pre">Queue</span></tt>, <tt class="docutils literal"><span class="pre">Value</span></tt>
  203. and <tt class="docutils literal"><span class="pre">Array</span></tt>. For example:</p>
  204. <pre class="literal-block">
  205. from processing import Process, Manager
  206. def f(d, l):
  207. d[1] = '1'
  208. d['2'] = 2
  209. d[0.25] = None
  210. l.reverse()
  211. if __name__ == '__main__':
  212. manager = Manager()
  213. d = manager.dict()
  214. l = manager.list(range(10))
  215. p = Process(target=f, args=(d, l))
  216. p.start()
  217. p.join()
  218. print d
  219. print l
  220. </pre>
  221. <p>will print</p>
  222. <pre class="literal-block">
  223. {0.25: None, 1: '1', '2': 2}
  224. [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  225. </pre>
  226. <p>Creating managers which support other types is not hard --- see
  227. <a class="reference" href="manager-objects.html#customized-managers">Customized managers</a>.</p>
  228. <p class="last">Server process managers are more flexible than using shared memory
  229. objects because they can be made to support arbitrary object types.
  230. Also, a single manager can be shared by processes on different
  231. computers over a network. They are, however, slower than using
  232. shared memory. See <a class="reference" href="manager-objects.html#server-process-managers">Server process managers</a>.</p>
  233. </dd>
  234. </dl>
  235. </div>
  236. <div class="section">
  237. <h1><a id="using-a-pool-of-workers" name="using-a-pool-of-workers">Using a pool of workers</a></h1>
  238. <p>The <tt class="docutils literal"><span class="pre">Pool()</span></tt> function returns an object representing a pool of worker
  239. processes. It has methods which allows tasks to be offloaded to the
  240. worker processes in a few different ways.</p>
  241. <p>For example:</p>
  242. <pre class="literal-block">
  243. from processing import Pool
  244. def f(x):
  245. return x*x
  246. if __name__ == '__main__':
  247. pool = Pool(processes=4) # start 4 worker processes
  248. result = pool.applyAsync(f, [10]) # evaluate &quot;f(10)&quot; asynchronously
  249. print result.get(timeout=1) # prints &quot;100&quot; unless your computer is *very* slow
  250. print pool.map(f, range(10)) # prints &quot;[0, 1, 4,..., 81]&quot;
  251. </pre>
  252. <p>See <a class="reference" href="pool-objects.html">Process pools</a>.</p>
  253. </div>
  254. <div class="section">
  255. <h1><a id="speed" name="speed">Speed</a></h1>
  256. <p>The following benchmarks were performed on a single core Pentium 4,
  257. 2.5Ghz laptop running Windows XP and Ubuntu Linux 6.10 --- see
  258. <a class="reference" href="../examples/benchmarks.py">benchmarks.py</a>.</p>
  259. <p><em>Number of 256 byte string objects passed between processes/threads per sec</em>:</p>
  260. <table border="1" class="docutils">
  261. <colgroup>
  262. <col width="55%" />
  263. <col width="16%" />
  264. <col width="29%" />
  265. </colgroup>
  266. <thead valign="bottom">
  267. <tr><th class="head">Connection type</th>
  268. <th class="head">Windows</th>
  269. <th class="head">Linux</th>
  270. </tr>
  271. </thead>
  272. <tbody valign="top">
  273. <tr><td>Queue.Queue</td>
  274. <td>49,000</td>
  275. <td>17,000-50,000 <a class="footnote-reference" href="#id2" id="id1" name="id1">[1]</a></td>
  276. </tr>
  277. <tr><td>processing.Queue</td>
  278. <td>22,000</td>
  279. <td>21,000</td>
  280. </tr>
  281. <tr><td>Queue managed by server</td>
  282. <td>6,900</td>
  283. <td>6,500</td>
  284. </tr>
  285. <tr><td>processing.Pipe</td>
  286. <td>52,000</td>
  287. <td>57,000</td>
  288. </tr>
  289. </tbody>
  290. </table>
  291. <table class="docutils footnote" frame="void" id="id2" rules="none">
  292. <colgroup><col class="label" /><col /></colgroup>
  293. <tbody valign="top">
  294. <tr><td class="label"><a class="fn-backref" href="#id1" name="id2">[1]</a></td><td>For some reason the performance of <tt class="docutils literal"><span class="pre">Queue.Queue</span></tt> is very
  295. variable on Linux.</td></tr>
  296. </tbody>
  297. </table>
  298. <p><em>Number of acquires/releases of a lock per sec</em>:</p>
  299. <table border="1" class="docutils">
  300. <colgroup>
  301. <col width="60%" />
  302. <col width="20%" />
  303. <col width="20%" />
  304. </colgroup>
  305. <thead valign="bottom">
  306. <tr><th class="head">Lock type</th>
  307. <th class="head">Windows</th>
  308. <th class="head">Linux</th>
  309. </tr>
  310. </thead>
  311. <tbody valign="top">
  312. <tr><td>threading.Lock</td>
  313. <td>850,000</td>
  314. <td>560,000</td>
  315. </tr>
  316. <tr><td>processing.Lock</td>
  317. <td>420,000</td>
  318. <td>510,000</td>
  319. </tr>
  320. <tr><td>Lock managed by server</td>
  321. <td>10,000</td>
  322. <td>8,400</td>
  323. </tr>
  324. <tr><td>threading.RLock</td>
  325. <td>93,000</td>
  326. <td>76,000</td>
  327. </tr>
  328. <tr><td>processing.RLock</td>
  329. <td>420,000</td>
  330. <td>500,000</td>
  331. </tr>
  332. <tr><td>RLock managed by server</td>
  333. <td>8,800</td>
  334. <td>7,400</td>
  335. </tr>
  336. </tbody>
  337. </table>
  338. <p><em>Number of interleaved waits/notifies per sec on a
  339. condition variable by two processes</em>:</p>
  340. <table border="1" class="docutils">
  341. <colgroup>
  342. <col width="60%" />
  343. <col width="20%" />
  344. <col width="20%" />
  345. </colgroup>
  346. <thead valign="bottom">
  347. <tr><th class="head">Condition type</th>
  348. <th class="head">Windows</th>
  349. <th class="head">Linux</th>
  350. </tr>
  351. </thead>
  352. <tbody valign="top">
  353. <tr><td>threading.Condition</td>
  354. <td>27,000</td>
  355. <td>31,000</td>
  356. </tr>
  357. <tr><td>processing.Condition</td>
  358. <td>26,000</td>
  359. <td>25,000</td>
  360. </tr>
  361. <tr><td>Condition managed by server</td>
  362. <td>6,600</td>
  363. <td>6,000</td>
  364. </tr>
  365. </tbody>
  366. </table>
  367. <p><em>Number of integers retrieved from a sequence per sec</em>:</p>
  368. <table border="1" class="docutils">
  369. <colgroup>
  370. <col width="60%" />
  371. <col width="20%" />
  372. <col width="20%" />
  373. </colgroup>
  374. <thead valign="bottom">
  375. <tr><th class="head">Sequence type</th>
  376. <th class="head">Windows</th>
  377. <th class="head">Linux</th>
  378. </tr>
  379. </thead>
  380. <tbody valign="top">
  381. <tr><td>list</td>
  382. <td>6,400,000</td>
  383. <td>5,100,000</td>
  384. </tr>
  385. <tr><td>unsynchornized shared array</td>
  386. <td>3,900,000</td>
  387. <td>3,100,000</td>
  388. </tr>
  389. <tr><td>synchronized shared array</td>
  390. <td>200,000</td>
  391. <td>220,000</td>
  392. </tr>
  393. <tr><td>list managed by server</td>
  394. <td>20,000</td>
  395. <td>17,000</td>
  396. </tr>
  397. </tbody>
  398. </table>
  399. </div>
  400. </div>
  401. <div class="footer">
  402. <hr class="footer" />
  403. <a class="reference" href="index.html">Prev</a> &nbsp; &nbsp; &nbsp; &nbsp; <a class="reference" href="index.html">Up</a> &nbsp; &nbsp; &nbsp; &nbsp; <a class="reference" href="processing-ref.html">Next</a>
  404. </div>
  405. </body>
  406. </html>