什么是线程?
进程:资源单位
线程:执行单位
每一个进程中都默认有一个线程(称之为主线程)
为什么要用线程?
开一个进程:
需要申请内存空间 耗时
将代码拷贝到申请的内存空间中 耗时
开线程:
不需要申请内存空间
开线程的开销比开进程的开销小
如何使用线程?
一、开启线程的两种方式(和进程差不多相似)
from threading import Thread
import time
def task(name):
print('%s is running'% name)
time.sleep(1)
print('%s is over'% name)
if __name__ == '__main__':
t = Thread(target=task,args=('egon',))
t.start()
print('主')
输出:
egon is running
主
egon is over
方式二:
from threading import Thread
import time
class Mythred(Thread):
def __init__(self,name):
super().__init__()
self.name = name
def run(self):
print('%s is running'% self.name)
time.sleep(1)
print('%s is over' %self.name)
if __name__ == '__main__':
t = Mythred('tank')
t.start()
print('主')
输出:
egon is running
主
egon is over
二、join方法(优先加载子线程)
from threading import Thread
import time
def task(name):
print('%s is running' %name)
time.sleep(1)
print('%s is over'%name)
if __name__ == '__main__':
t = Thread(target=task,args=('geon',))
t.start()
t.join()
print('主')
输出:
egon is running
egon is over
主
三、线程之间内存空间相互隔离
from threading import Thread
import time
x = 100
def tash():
global x
print(x)
time.sleep(1)
x = 6000
print(x)
t = Thread(target=tash)
t.start()
t.join()
print(x)
输出:
100
6000
100
四、线程对象的其它属性
# active_count 返回当前活动链接数
# current_thread().name 获取当前线程的名字
from threading import Thread,active_count,current_thread
import os
import time
def task(name):
print('%s is running' %name,current_thread().name) #当前线程的名字
time.sleep(1)
print('%s is over' %name)
def info(name):
print('%s is running' %name,current_thread().getName()) #当前线程的名字另外一种表示方法
time.sleep(1)
print('%s is over' %name)
t = Thread(target=task,args=('xxx',))
t1 = Thread(target=info,args=('xxx',))
t.start()
t1.start()
print(active_count()) # 查看存活的线程数
print(os.getpid()) # 查看线程id
print(current_thread().name) #查看线程的名字(主线程MainThread)
输出结果:
xxx is running Thread-1
xxx is running Thread-2
3
14996
MainThread
xxx is over
xxx is over
五、守护线程
from threading import Thread
import time
def task(name):
print('%s is running'%name)
time.sleep(1)
print('%s is over'%name)
if __name__ == '__main__':
t = Thread(target=task,args=('xxx',))
t.daemon = True # 守护线程
t.start()
print('主')
输出:
xxx is running
主
六、互斥锁
from threading import Thread,Lock
import time
import random
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)
输出:
0