同步
<span class="hljs-keyword">import</span> time
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run</span><span class="hljs-params">(index)</span>:</span>
print(<span class="hljs-string">"sunck is a good man"</span>, index)
time.sleep(<span class="hljs-number">2</span>)
print(<span class="hljs-string">"sunck is a nice man"</span>, index)
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>):
run(i)
异步
说明:后面的课程中会使用到asyncio模块,现在的目的是使同学们理解异步思想
<span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> time
<span class="hljs-comment"># 定义一个异步函数(定义了一个协程)</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run</span><span class="hljs-params">()</span>:</span>
print(<span class="hljs-string">"sunck is a good man"</span>)
<span class="hljs-comment">#模拟一个耗时IO</span>
asyncio.sleep(<span class="hljs-number">2</span>)
print(<span class="hljs-string">"sunck is a nice man"</span>)
loop = asyncio.get_event_loop()
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>):
loop.run_until_complete(run())