Search This Blog

Wednesday, March 10, 2010

simple python thread example

<span class="k">import</span> <span class="nn">time</span>
<span class="k">from</span> <span class="nn">threading</span> <span class="k">import</span> <span class="n">Thread</span>

<span class="k">def</span> <span class="nf">myfunc</span><span class="p">(</span><span class="n">i</span><span class="p">):</span>
<span class="k">print</span> <span class="s">"sleeping 5 sec from thread </span><span class="si">%d</span><span class="s">"</span> <span class="o">%</span> <span class="n">i</span>
<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">5</span><span class="p">)</span>
<span class="k">print</span> <span class="s">"finished sleeping from thread </span><span class="si">%d</span><span class="s">"</span> <span class="o">%</span> <span class="n">i</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mf">10</span><span class="p">):</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">myfunc</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">i</span><span class="p">,))</span>
<span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>



No comments: