1.什么是线程
进程:资源单位
线程:执行单位
注意:每一个进程中都会自带一个线程
2.为什么要有线程
开一个进程:
申请内存空间 耗时
将代码拷贝到申请的内存空间中 耗时
开线程:
不需要申请内存空间
开线程的开销远远小于开进程的开销!!!
3.如何使用线程
4 子线程的两种建立方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 方式1 ''' from threading import Thread import time def task(name): print('%s is running' % name) time.sleep(1) print('%s is over') t = Thread(target=task, args=('king',)) t.start() print('主') ''' # 方式 2 from threading import Thread import time class MyThread(Thread): def __init__(self,name): super().__init__() self.name = name def run(self): print('%s is run'%self.name) time.sleep(3) print('%s is over'%self.name) t = MyThread('king') t.start() print('主')
5、线程之间的数据共享
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Thread x = 100 def task(): global x x =666 print(x) t = Thread(target=task) t.start() print(x)
6、线程互斥锁
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Thread,Lock import time mutex = Lock() n = 100 def task(): global n mutex.acquire() tmp = n time.sleep(0.1) n = tmp -1 mutex.release() t_list = [] for i in range(100): t = Thread(target=task) t.start() t_list.append(t) for t in t_list: t.join() print(n)
7、线程的其他属性方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from threading import Thread,active_count,current_thread import os import time def task(name): # print('%s is running'%name,os.getpid()) print('%s is running'%name,current_thread().name,current_thread().getName()) time.sleep(1) print('%s is over'%name) def info(name): print('%s is running' % name, current_thread().name, current_thread().getName()) time.sleep(1) print('%s is over' % name) t = Thread(target=task,args=('关磊',)) t1 = Thread(target=info,args=('关超',)) t.start() t1.start() t.join() print(active_count()) # 当前存活的线程数 print(os.getpid()) print(current_thread().name) print(current_thread().getName())