Python并发编程—线程

线程编程(Thread)

线程基本概念

1.什么是线程
【1】 线程被称为轻量级的进程
【2】 线程也可以使用计算机多核资源,是多任务编程方式
【3】 线程是系统分配内核的最小单元
【4】 线程可以理解为进程的分支任务

2.线程特征
【1】 一个进程中可以包含多个线程
【2】 线程也是一个运行行为,消耗计算机资源
【3】 一个进程中的所有线程共享这个进程的资源
【4】 多个线程之间的运行互不影响各自运行
【5】 线程的创建和销毁消耗资源远小于进程
【6】 各个线程也有自己的ID等特征

threading模块创建线程

【1】 创建线程对象

from threading import Thread 

t = Thread()

  • 功能:创建线程对象
  • 参数:target 绑定线程函数
  •    args 元组 给线程函数位置传参
  •    kwargs 字典 给线程函数键值传参

【2】 启动线程

t.start()

【3】 回收线程

t.join([timeout])

 1 import threading
 2 from time import sleep
 3 import os
 4 
 5 a = 1
 6 
 7 # 线程函数
 8 def music():
 9   for i in range(3):
10     sleep(2)
11     print(os.getpid(),"播放黄河大合唱")
12   global a
13   print("a = ",a)
14   a = 10000
15 
16 # 创建线程对象
17 t = threading.Thread(target = music)
18 t.start() # 启动线程
19 
20 for i in range(4):
21   sleep(1)
22   print(os.getpid(),"播放葫芦娃")
23 
24 t.join() # 回收线程
线程使用示例1
 1 from threading import Thread
 2 from time import sleep
 3 
 4 # 含有参数的线程函数
 5 def fun(sec,name):
 6   print("线程函数参数")
 7   sleep(sec)
 8   print("%s 线程完毕"%name)
 9 
10 # 创建多个线程
11 jobs = []
12 for i in range(5):
13   t = Thread(target = fun,args=(2,),
14              kwargs={'name':'T%d'%i})
15   jobs.append(t)
16   t.start()
17 
18 for i in jobs:
19   i.join()
线程使用示例2

猜你喜欢

转载自www.cnblogs.com/maplethefox/p/10989193.html
今日推荐