加入收藏 | 设为首页 | 会员中心 | 我要投稿 大庆站长网 (https://www.0459zz.com/)- 科技、智能边缘云、事件网格、云计算、站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python:线程

发布时间:2020-07-30 05:42:56 所属栏目:Python 来源:互联网
导读:线程1,线程与进程进程:执行中的程序。进程可以处理一个任务。对于一个人来说一个人就是一个进程。进程被包含着线程。线程:轻量级的进程。一个时间点只做一件事。一个人可以做的多件事情,每一件事情都是一个线程。2,线程是CPU调度的最小单位。进程是资源

<h1 style="text-align: center">线程

1,线程与进程

2,线程是CPU调度的最小单位。进程是资源分配的最小单位

3,开启线程的时空开销 都比 开启进程要小,且cpu在线程之间切换比在进程之间切换快。

4,一个程序中 可以同时有多进程和线程

1)调用模块开启线程

threading <span style="color: #0000ff">def func(): <span style="color: #008000">#<span style="color: #008000"> 子线程
time.sleep(1<span style="color: #000000">)
<span style="color: #0000ff">print(<span style="color: #800000">'<span style="color: #800000">hello world<span style="color: #800000">'<span style="color: #000000">,os.getpid())
thread_lst =<span style="color: #000000"> []
<span style="color: #0000ff">for i <span style="color: #0000ff">in range(10<span style="color: #000000">):
t = Thread(target=<span style="color: #000000">func)
t.start()
thread_lst.append(t)
[t.join() <span style="color: #0000ff">for t <span style="color: #0000ff">in<span style="color: #000000"> thread_lst]
<span style="color: #0000ff">print(os.getpid()) <span style="color: #008000">#<span style="color: #008000"> 主线程

2)调用类开启线程

threading <span style="color: #0000ff">class<span style="color: #000000"> MyThread(Thread):
count = 0 <span style="color: #008000">#<span style="color: #008000"> 静态属性
<span style="color: #0000ff">def <span style="color: #800080">init<span style="color: #000000">(self,arg1,arg2):
super().<span style="color: #800080">init<span style="color: #000000">()
self.arg1 =<span style="color: #000000"> arg1
self.arg2 =<span style="color: #000000"> arg2
<span style="color: #0000ff">def<span style="color: #000000"> run(self):
MyThread.count += 1<span style="color: #000000">
time.sleep(1<span style="color: #000000">)
<span style="color: #0000ff">print(<span style="color: #800000">'<span style="color: #800000">%s,%s,%s<span style="color: #800000">'%<span style="color: #000000">(self.arg1,self.arg2,self.name,os.getpid()))

<span style="color: #0000ff">for i <span style="color: #0000ff">in range(10<span style="color: #000000">):
t = MyThread(i,i<span style="color: #800000">'<span style="color: #800000"><span style="color: #800000">'<span style="color: #000000">)
t.start()
<span style="color: #0000ff">print(t.count)

(编辑:大庆站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读