1 什么是线程:
进程其实一个资源单位,而进程内的线程才是cpu上的执行单位
线程其实指的就是代码的执行过程
2 为何要用线程:
线程vs进程
1. 同一进程下的多个线程共享该进程内的资源
2. 创建线程的开销要远远小于进程
3 如何用线程:
方式一:
from threading import Thread
import time
def task(name):
print('%s is running' %name)
time.sleep(2)
print('%s is done' %name)
if __name__ == '__main__':
t=Thread(target=task,args=('线程1',))
t.start()
print('主')
方式二:
from threading import Thread
import time
class Mythread(Thread):
def run(self):
print('%s is running' %self.name)
time.sleep(2)
print('%s is done' %self.name)
if __name__ == '__main__':
t=Mythread()
t.start()
print('主')
线程特性:
from threading import Thread
import time
n=100
def task():
global n
n=0
if __name__ == '__main__':
t=Thread(target=task)
t.start()
t.join()
print('主',n)
from threading import Thread
import time,os
def task():
print('%s is running' %os.getpid())
if __name__ == '__main__':
t=Thread(target=task)
t.start()
print('主',os.getpid())
from threading import Thread,active_count,current_thread
import time,os
def task():
print('%s is running' %current_thread().name)
time.sleep(2)
if __name__ == '__main__':
t=Thread(target=task,)
t.start()
# t.join()
# print('主',active_count())
print('主',current_thread().name)
守护线程:
from threading import Thread
import time
def task(name):
print('%s is running' %name)
time.sleep(2)
print('%s is done' %name)
if __name__ == '__main__':
t=Thread(target=task,args=('线程1',))
t.daemon=True
t.start()
print('主')
from threading import Thread
from multiprocessing import Process
import time
def foo():
print(123)
time.sleep(1)
print("end123")
def bar():
print(456)
time.sleep(3)
print("end456")
if __name__ == '__main__':
# t1=Thread(target=foo)
# t2=Thread(target=bar)
t1=Process(target=foo)
t2=Process(target=bar)
t1.daemon=True
t1.start()
t2.start()
print("main-------")
'''
123
main-------
456
end456
'''
'''
main-------
123
456
end456
'''
'''
main-------
456
end456
'''
互斥锁:
from threading import Thread,Lock
import time
mutex=Lock()
n=100
def task():
global n
mutex.acquire()
temp=n
time.sleep(0.1)
n=temp-1
mutex.release()
if __name__ == '__main__':
t_l=[]
for i in range(100):
t=Thread(target=task)
t_l.append(t)
t.start()
for t in t_l:
t.join()
print(n)