python:线程
发布时间:2020-12-17 00:01:18 所属栏目:Python 来源:网络整理
导读:h1 style="text-align: center"线程 1,线程与进程 2,线程是CPU调度的最小单位。进程是资源分配的最小单位 3,开启线程的时空开销 都比 开启进程要小,且cpu在线程之间切换比在进程之间切换快。 4,一个程序中 可以同时有多进程和线程 1)调用模块开启线程
<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">): (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |