一、进程与线程
1. 一个程序至少有一个进程,一个进程至少有一个线程
2. 线程的划分尺度小于进程,使得多线程程序的并发性高
3. 进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率
4. 每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制
5. 多线程的意义在于一个应用程序中,有多个执行部分可以同时执行。但操作系统并没有将多个线程看做多个独立的应用,来实现进程的调度和管理以及资源分配
当界面有大量的任务需要更新的时候 需要放入分线程
import threading
# 获取当前线程的名称 main主要的
print('当前线程为',threading.current_thread().name)
def myThread():
print('位置1',threading.current_thread().name)
print('位置2', threading.current_thread().name)
print('位置3', threading.current_thread().name)
myThread()
class People(object):
def thread_test(self):
print('对象方法',threading.current_thread().name)
p = People()
p.thread_test()
# threading.Thread开辟一个新的线程 target目标 name分线程名称
sub_thread = threading.Thread(target=myThread,name='newThread')
# 开始执行跟线程
sub_thread.start()
# 确保任务执行的顺序 自己的线程先完成之后再执行其他线程
sub_thread.join()
# 当程序运行时,会先在主线程中执行(因为在程序刚开始的时候只有主线程,没有分线程)
# 然后会根据情况进入到分线程,主线程和分线程的任务是交叉进行的,(因为两个线程两条路)
# 自己线程的执行情况不会影响对方线程
# 所以感觉是交叉的 分线程结束以后,会回归到主线程
print('outside1',threading.current_thread().name)
print('outside2',threading.current_thread().name)
print('outside3',threading.current_thread().name)
线程锁:当一个数据有多个线程都可以对其修改的时候,任何一个线程的改变都会被其他线程造成影响;如果某一个线程在使用完之前,其他线程不能对其修改,就需要对这个线程增加一个线程锁。
count = 0
def get_money(money):
global count
count += money
count += money
count -= money
# 创建一个线程锁对象
lock = threading.Lock()
def lock_thread(money):
# acquire捕获
# 加锁
lock.acquire()
time.sleep(random.randint(1,3))
print('当前线程为',threading.current_thread().name)
get_money(money)
time.sleep(random.randint(1,3))
print('当前线程为', threading.current_thread().name)
# 解锁
lock.release()
# 创建线程的参数为一个元组类型
# 主线程开辟一个分线程
thread1 = threading.Thread(target=lock_thread,name='thread1',args=(1000,))
thread2 = threading.Thread(target=lock_thread,name='thread2',args=(2000,))
thread1.start()
thread2.start()
print('hello world')
# join 注重的整体,线程1没有执行完,线程2不能执行
# lock 注重的是局部 某一个变量没有用完,其他线程不能使用
# thread1.join()
# thread2.join()
线程队列:首先引入一个包 import queue
import queue
# 创建一个线程队列
# 队列 :first in first out 先进先出
q = queue.Queue()
for i in range(5):
# 将内容放入到线程队列中
q.put(i)
while not q.empty():
print(q.get())
# LIFO last in first out 后进先出
p = queue.LifoQueue()
for i in range(5):
p.put(i)
while not p.empty():
print(p.get())
二、yield与return的区别
return和yield的区别:(1)return可以往法外传递一个值 ,从之后return之后的代码不再执行
(2)yield 也可以往方法里面传递一个值,但是传递之后继续执行后面的代码;并且通过yield传递的值
的方法是一个可迭代对象。
#return
def test1(name):
print('return方法')
return name
print('return方法结束')
name = test1('zhangsan')
print(name)
# yield
def test2(age):
for i in range(age):
yield i
print('hello')
for x in test2(18):
print('x=',x)