线程


import threading
import time
'''
所有程序都是cpu执行的 解释器(Cpython)就是翻译成cpu的语言 操作系统(os)才能调动cpu
一个.py文件就是一个进程

一个线程就是一堆指令集
线程:
假设你正在读一本书,你现在想休息一下,但是你想从你停止的地方回来继续阅读。实现此目的的一种方法是将页码、行号和字号标记下来。
正在读书的执行环境是这三个数字。
如果你有一个室友,她用了同样的方法,她可以在你不用的时候拿起这本书,从她停下的地方开始读。然后你可以把它拿回去,从你原来的地方继续
进程:
最后:线程与进程不同。线程是执行的上下文,而进程是一组与计算相关的资源。一个进程可以有一个或多个线程。

io密集型任务或函数 计算密集型任务或函数

GIL:
在同一时刻只能有一个线程进入解释器
解决方法:
协程+多进程
if 任务是io密集型的可以用python
if 任务是计算密集型的可以改用C, python 不太行

threading模块:

启动方式:
t1 = 线程 t2 = threading
list.append(t1) list.append(t2)
for i in list
i.start()

join():
在子线程结束之后,在执行主线程
for t in threads:
t.start
t.join #for 没有作用域权限 只有函数 类 模块可以 这个i 就是最后一个赋值 也就是t2
重要******谁被join住 就必须等被join的线程运行完 全部线程才能往下执行*****

Daemeon():
for t in threads:
t.setDaemeon(True) 每个守护线程
t.start
被守护线程是只要其他的线程执行完就结束了 不会等待被守护线程执行完毕
守护线程 不守护(抛弃)
threading.current_thread():
拿到当前线程的名字 = thread-1
threading.active_count():
活着的线程数 count计数
。join 就剩一个主线程了 子线程结束

线程锁:
开100的线程,设一个全局变量100,线程1拿到100,线程2也拿到100 都去减1 所以得到99
把全局变量赋值给temp,在全局变量=temp-1 得到结果0,1,2,3 覆盖了1,2,3次线程
r = threading.Lock()
加锁:r.acquire()
解锁:r.release()
锁的就是计算部分 也就是锁的是线程 不锁的部分还是执行的 只是针对有锁的线程
GIL和加锁 各有功能不同 所以需要自己加锁

for i in range(5):list.append(MyThread())
for i in list:i.start() 以上都是调用方法

死锁和递归锁:
线程1 = 加锁AB 解锁BA 加锁BA 解锁A
线程2 = 加锁A B A释放 B解锁 但是线程1=第二次B 没解锁 死锁
look = threading.RLock #递归锁
look.acquire()
look.release()
{'A':'A','B':'B','B':'B','A':'A',} 字典形式的递归锁 加锁 解锁 有计数了

信号量:
count = 4 可以同时进去线程 相当于4个停车位 停满以后 出去1个 才能进来一个
semaphore = threading.BoundedSemaphore(5 开几个停车位)
以后连接数据库的连接池

randint(0,100) 随机创建一个0-100的数
条件变量:
lock_con = threading.Condition(Rlook)
.wait() 条件不满足时调用,线程会释放锁并进入等待阻塞
.notify() 条件创造后调用,通知等待池激活一个线程
.notfyAll() 条件创造后调用,通知等待池激活所有线程。
试着自己写写生产者和消费者

Event: 事件
event.isSet() 返回event的状态值
event.wait() 如果event。siSet()== False 将阻塞线程
event.set() 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态,等待操作系统调度
event。clear()恢复event的状态值为False。

重要 多线程利器
队列:queue 数据结构 放数据
import queue
d = queue.Queue(max size,默认值是无限大)一般不写
d.put('随便',0or1 会不会报错) 插入数据 设置不够队列的 阻塞
d.get()不需要参数 取数据 是有顺序的 默认是先进先出 fifo first in first out 也会阻塞住 等待进入
d.lifoQueue([maxsize]):LIFO 列队模式。后进先出
d.priorityQueue([maxsize]):最优先级队列模式,使用此列时,项目应该是(priority,data)的形式 优先级进出
put(item[block,[timeout]]) item放入队列,如果block设置为Ture【默认】时,队列满了,调用者阻塞,否则抛出full异常
timeout设置阻塞超时
get([block,[timeout]]) 队列中拿出项目
qsize() 返回队列大小 还剩几个
full() 如果队列满了返回true 否则false
empty() 如果队列为空返回True 否则false
写写吃包子


'''

'''
import threading
import time

stat=time.time()
def foo(a):

time.sleep(a)
print('foo')
def bar(a):

time.sleep(a)
print('bar')




t1 = threading.Thread(target=foo,args=(8,))
t1.start()
t2 = threading.Thread(target=bar,args=(8,))
t2.start()
t1.join()
t2.join()
end = time.time()
print(end-stat,'wan')

start = time.time()
def foo():
for i in range(2):
print('11111')
time.sleep(2)
print('22222')

def bar():
for i in range(2):
print('3333333')
time.sleep(5)
print('4444444')

end = time.time()
print(end - start)
print(end-start) #主程序就直接执行完了 0.0
if __name__ == '__main__':
threads = []
t1 = threading.Thread(target=foo,)
t2 = threading.Thread(target=bar,)
print(end - start,'wwwwww')
threads.append(t1)
threads.append(t2)
for i in threads:
i.start()
print('555555')



class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)

def run(self):

global num
r.acquire()
temp = num
time.sleep(0.1)
num = temp - 1
r.release()

num = 10

if __name__ == '__main__':
r = threading.Lock() #不加括号 拿到对象 没有实例化

list = []
for i in range(10):
t = MyThread()

t.start()
list.append(t)

for i in list:
i.join()
print('game over',num)
'''

import queue
import threading
import time
from random import randint
class Mythread(threading.Thread):
def __init__(self):
super(Mythread,self).__init__()#第一个参数 类名 第二个 self 。init
def run(self):
while True:
r = randint(0,100)
re = q.put(r)
print('zuobaozi%s'%r)
time.sleep(1)
class Chibaozi(threading.Thread):
def run(self):
while True:
re = q.get()
print('chibaozi%s'%re)
if __name__ == '__main__':
q = queue.Queue()
list_threads = [Mythread(),Mythread(),Mythread(),Chibaozi()]

for i in list_threads:
i.start()

for i in list_threads:
i.join()









原文地址:https://www.cnblogs.com/xuexihainan/p/12499135.html